I have a date that is being returned in a string format
string utcdt = "2017-01-01T15:48:00-07:00";
How could I extract the 07:00
Mountain Time from the string above and format any date to this regional formatting?
I do not want to change timezones on my computer, as the UTC time returned to the variable utcdt
can vary depending, and all other dates used in my WinForm app would need to conform to the same timezone specifications.
Edit
I am using the FEDEx API and this is one format of the date returnerd
string utcdt = "2017-01-01T15:48:00-07:00";
Now later in the application there is
foreach (TrackingDateOrTimestamp timestamp in trackDetail.DatesOrTimes)
Console.WriteLine("{0}: {1}", timestamp.Type, timestamp.DateOrTimestamp);
Which returns the data in my local time - meaning
01/01/2017 17:48:00
I am trying to come up with a solution to have the dates be consistent.
You can use the DateTimeOffset
class to parse the string into the local time and it's offset from UTC. You can then save the offset as a TimeSpan
.
Later on then again use the DateTimeOffset
class to convert another DateTime
you have to use the same offset:
string dto = "2017-01-01T15:48:00-07:00";
DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(dto);
DateTime utcDateTime = dateTimeOffset.UtcDateTime;
TimeSpan timezoneOffset = dateTimeOffset.Offset;
MessageBox.Show("UTC DateTime: " + utcDateTime);
MessageBox.Show("Offset: " + timezoneOffset);
DateTimeOffset nowWithOffset = DateTimeOffset.UtcNow.ToOffset(timezoneOffset);
MessageBox.Show("Now in other timezone: " + nowWithOffset.ToString("O"));
Note what other commentators have written: This does not correctly deal with Daylight Saving Time. In order to deal with that, you actually need to know the real timezone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.