-2

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 yyyy-MM-ddThh:mm:ssZ, 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 toTimeFormat is being converted to the 12h system, so when I use it later it's being considered as 6:00 AM.

Any ideas please?

Husain Alhamali
  • 823
  • 4
  • 17
  • 32

1 Answers1

2

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");
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364