Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove UtcOffset from DateTime.Now

I need the value of DateTime.Now in round trip format without the utcOffset. Based on the this MSDN article if you create a new instance of DateTime without the UtcOffset it produces the format I want.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
// Displays 2008-04-10T06:30:00.0000000   

but if I use DateTime.Now, i get the offset in the string:

DateTime.Now.ToString("o")
// Displays 2012-02-08T14:11:12.8378703-05:00   

I could just use substring or populate a DateTime instance without it, but I was wondering if there is a way to remove the UtcOffset.

like image 300
Josh Avatar asked Feb 08 '12 19:02

Josh


2 Answers

The UTC offset (e.g., "-05:00" or "Z") is omitted if the DateTime.Kind is neither Utc nor Local.

You can create such a DateTime value as follows:

DateTime.UtcNow.ToString("o");
// "2012-02-08T19:19:38.5767158Z"

new DateTime(DateTime.UtcNow.Ticks).ToString("o");
// "2012-02-08T19:19:38.5767158"

new DateTime(DateTime.Now.Ticks).ToString("o");
// "2012-02-08T14:19:38.5767158"
like image 135
dtb Avatar answered Sep 20 '22 11:09

dtb


If I understand what you want, you can use DateTime.UtcNow.

DateTime.Now.ToString("o")
DateTime.UtcNow.ToString("o")

Outputs:

2012-02-08T13:18:22.4459488-06:00
2012-02-08T19:18:22.4599488Z
like image 42
Austin Salonen Avatar answered Sep 18 '22 11:09

Austin Salonen