C# - UTC自动转换为12h系统

时间:2016-11-06 12:57:55

标签: c# date datetime

我正在使用一个项目,其功能要求之一是创建一个日期时间范围,我将根据该范围选择一组数据。

这个范围应该是今天的日期时间从8:00:00到18:00:00,然后我想将格式转换为yyyy-MM-ddThh:mm:ssZ,所以我在做以下是:

DateTime fromTime = DateTime.Now;
TimeSpan ts = new TimeSpan(8,0,0);
fromTime = fromTime.Date + ts;
string fromTimeFormat = fromTime.ToString("yyyy-MM-ddThh:mm:ssZ");
DateTime toTime = DateTime.Now;
TimeSpan tss = new TimeSpan(18, 0, 0);
toTime = toTime.Date + tss;
string toTimeFormat = toTime.ToString("yyyy-MM-ddThh:mm:ssZ");

问题在于,toTimeFormat正在转换为12h系统,所以当我以后使用它时,它被认为是6:00 AM。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

因为您使用hh specifier格式的12-hour clock

您需要使用HH specifier格式的24-hour clock

string toTimeFormat = toTime.ToString("yyyy-MM-ddTHH:mm:ssZ");

您可以简化代码;

string fromTimeFormat = DateTime.Today.AddHours(6).ToString("yyyy-MM-ddThh:mm:ssZ");   
string toTimeFormat = DateTime.Today.AddHours(18).ToString("yyyy-MM-ddTHH:mm:ssZ");
相关问题