Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.AddHours gives wrong output and datetime format changes

Tags:

c#

datetime

I want DateTime in the following format.

DateTime a = Convert.ToDateTime(DateTime.UtcNow.ToString("s") + "Z");

Output:

2018-05-29T09:16:59Z

I want to subtract 4 hours from this time. So I have used this line of code:

var result = a.AddHours(-4);

Now, not only is the wrong time being shown, the above format is also disturbed.

29-05-2018 10:52:51

Expected Output:

2018-05-29T05:16:59Z
like image 266
Hello Avatar asked Nov 08 '22 06:11

Hello


1 Answers

To get UTCNow minus 4 hours you'd want to do:

var fourHoursAgo = DateTime.UtcNow.AddHours(-4);
Console.WriteLine("fourHoursAgo: " + fourHoursAgo.ToString("yyyy-MM-ddTHH:mm:ssK"));

This will give an output like:

2018-05-29T05:36:18Z

This is basically an ISO 8601 format, very similar to DateTime.ToString("s"), but including the timezone ("Z" in this case.)

like image 200
Terry Lennox Avatar answered Nov 30 '22 00:11

Terry Lennox