Ali Alhamaly Ali Alhamaly - 3 months ago 24
C# Question

C# - UTC automatically convert to 12h system

I'm working with a project and one of its functional requirement is to create a datetime range in which I will select a set of data based on that.

This range should take today's datetime starting from 8:00:00 to 18:00:00, and then I want to convert the format to be

, so I'm doing the following to approach that:

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");

The problem is that, the
is being converted to the 12h system, so when I use it later it's being considered as 6:00 AM.

Any ideas please?


Because you are using hh specifier which is for 12-hour clock format.

You need to use HH specifier which is for 24-hour clock format.

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

And you can simplify your code as;

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