I need to convert the string "Fri Sep 11 00:00:00 GMT+04:00 2020"
into a DateTime
object 11.09.2011
.
When I use
DateTime result;
DateTime.TryParseExact(MyString, "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
result
is equal to {9/10/2020 11:00:00 PM}
.
How can I modify the code so that the date component is 11.09.2011
and not 10.09.2011
(I only need the date and don't care about the time) ?
Parse into a DateTimeOffset
instead, given that you've got an offset. From the documentation of the zz
specifier that you're using:
With DateTime values, the "zz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours. It does not reflect the value of an instance's DateTimeKind property. For this reason, the "zz" format specifier is not recommended for use with DateTime values.
So you'd end up with:
DateTimeOffset result;
bool success = DateTimeOffset.TryParseExact
(text, "ddd MMM dd HH:mm:ss 'GMT'zzz yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
From there, you can take the DateTime
part, which will be midnight on September 11th.
If you want just a date, you could use my Noda Time project to create a LocalDate
:
LocalDate = OffsetDateTime.FromDateTimeOffset(result).LocalDateTime.Date;
(I'd love to suggest parsing directly to OffsetDateTime
, but we haven't got support for that yet. We're hoping to include it in version 1.2.)
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