I have an excel sheet with a date I get out using some JavaScript or VBA (doesn't matter).
Then I end up having a date that looks like this: "Tue Feb 4 00:00:00 UTC+0100 2014"
Are there any build in versions to convert this to C# DateTime? As you can see then I don't use the time part, and thus also don't care about the UTC offset.
Are there any build in versions to convert this to C# DateTime?
Sure! You can use DateTime.TryParseExact
or DateTime.ParseExact
methods to parse your string.
string s = "Tue Feb 4 00:00:00 UTC+0100 2014";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM d HH:mm:ss 'UTC+0100' yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
In Custom Date and Time Format Strings page; if your string has signed offset, using DateTimeOffset
instead of DateTime
is recommended.
With
DateTime
values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. It does not reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values.With
DateTimeOffset
values, this format specifier represents theDateTimeOffset
value's offset from UTC in hours and minutes.
string s = "Tue Feb 4 00:00:00 UTC+0100 2014";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss 'UTC'zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Then you can convert this DateTimeOffset
to DateTime
. Because a DateTime
doesn't store any offset value. There is no such a thing like; "a DateTime
with an offset as 1 hour"
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.