Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a UTC date?

Tags:

c#

datetime

I have two strings timestamp and an UTC offset.

"timestamp":"2014-03-18T06:40:40+00:00","utc_offset":"+02:00"

I am trying to find a way to use these two to parse and create a UTC date.

I am able to parse the timestamp to DateTime, but not find help from the standard DateTime classes to parse the utc_offset and couldn't add the offset to the timestamp.

Without going to String manipulation, is there a standard way to handle this?

like image 805
SaravananArumugam Avatar asked Dec 09 '25 09:12

SaravananArumugam


1 Answers

You will have to create a TimeSpan object and add it to your DateTime.

TimeSpan tspan = TimeSpan.Parse("-02:00");
Console.WriteLine(tspan);   //This will print -02:00:00

See the following answer on how to convert an offset string ("+02:00") to a TimeSpan:

How to convert string offset to timespan in c#

EDIT: Please note that if you have the character '+' in your offset string, you will have to remove it before performing TimeSpan.Parse("offsetString"). This is the only string manipulation required. A negative offset requires the '-' character, but that should be obvious.

like image 131
PaulG Avatar answered Dec 11 '25 22:12

PaulG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!