How to parse timezone from datetime to datetime parameter

I use the saber API to book a flight.

I have a DateTime object that requires a parameter with a time zone. Entrance should be like "2016-03-01T10:00:00-06:00"

I am currently getting the value as

 DateTime dt = DateTime.UtcNow; string date = dt.ToString(); string tstamp = dt.ToString("mm-dd-yyyyTHH:mm:sszzz"); DateTimeOffset tstamp = DateTimeOffset.Parse(date); DateTime datetime = tstamp.DateTime; 

but when I put it back in DateTime , the timezone is automatically deleted. I cannot convert the object to DateTimeoffset because the API requires it in DateTime format.

+6
source share
2 answers

I think this can help you, you can get the right date, or get the offset as a TimeSpan, and then add it to your datetime, if necessary, or save it.

Edit: now I see that you just need to get the string from the DateTimeOffset object, not from the DateTime object.

 DateTime dt = DateTime.UtcNow; string date = dt.ToString(); string tstampString = dt.ToString("MM-dd-yyyyTHH:mm:ssZZZ"); DateTimeOffset tstampDT = DateTimeOffset.Parse(date); DateTime datetimeCurrent = tstampDT.DateTime; DateTime datetimeUTC = tstampDT.UtcDateTime; DateTime datetimeLocal = tstampDT.LocalDateTime; TimeSpan offsetFromUTC = tstampDT.Offset; 

edit:

 string tstampOffsetString = tstampDT.ToString("MM-dd-yyyyTHH:mm:sszzz"); 
+2
source

I am trying to explain a few things:

I have a DateTime object that requires a timezone parameter.

No, you do not.

A DateTime has no implicit format. It just has a date and time value. The concept of "Format" is applied only when you get a textual representation (aka string ). That way you might have a string with an offset part, but not a DateTime.

but when I put it back in DateTime, the timezone is deleted automatically ..

And DateTime itself does not contain real-time information. He may know if it is UTC or Local , but not what local actually means. Also DateTimeOffset has no time zone information. It just has DateTime and UTC Offset . But this data is not enough to determine the time zone, since different time intervals can have the same offset.

But if you really want to generate the input "2016-03-01T10:00:00-06:00" , I can provide two ways, I don’t even suggest

A Genereate-related DateTime instance based on this value sets the time zone of your system, which is 6 hours behind as part offfset (since using the zzz format specifier is not recommended for DateTime, which is not related to the Kind property) and formats your DateTime as;

 DateTime dt = new DateTime(2016, 3, 1, 10, 0, 0); Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:sszzz")); // 2016-03-01T10:00:00-06:00 

Create an instance of DateTimeOffset based on this DateTime and the offset part, after you format it as:

 var dto = new DateTimeOffset(dt, TimeSpan.FromHours(-6)); Console.WriteLine(dto.ToString("yyyy-MM-ddTHH:mm:sszzz")); // 2016-03-01T10:00:00-06:00 
0
source

All Articles