I am trying to get the local datetime with reference to UTC time gap and I am executing this code below.
var dtString =DateTime.UtcNow.ToString(@"yyyy-MM-ddTHH\:mm\:ss.fzzz");
but every time it return me an exception as
Why this exception is there, how to get this fixed?
The z
format specifier is used to show the offset between local time and UTC time.
It does not make sense to use it with the UTC time (since it is always 0). That is why you get a warning (thanks to @HansPassant for this remark).
You can either:
Want to print the local time and the offset to the UTC (which is standard):
var dtString = DateTime.Now.ToString(@"yyyy-MM-ddTHH\:mm\:ss.f zzz");
Or want to print the UTC time and the local time zone (which is REALLY not common):
var dtString = DateTime.UtcNow.ToString(@"yyyy-MM-ddTHH\:mm\:ss.f") + " " + DateTime.Now.ToString(@"zzz");
Which is more or less equivalent to your code (as explained in @JeroenMostert link):
var dtString = DateTime.UtcNow.ToString(@"yyyy-MM-ddTHH\:mm\:ss.fzzz");
But the resulting string is not standard at all and lead to misinterpretation.
"2015-02-18T12:08:15.1 +01:00"
Is read as local time and local time zone, not UTC time and local time zone.
Also you can find more information about time zone and good examples here : TimeZone.CurrentTimeZone Property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With