Josh Josh - 3 months ago 26
C# Question

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.

dtb dtb
Answer Source

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"