Create DateTime from string without applying timezone or daylight savings
How do I create a DateTime var from开发者_如何学Go a string which is already adjusted for UTC? I am running this on a machine set to BST (GMT+1). If I run the following line of code:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00");
and then use the value in a test against a database holding (UTC) values then it would appear that the Convert.ToDateTime() is actually giving me a UTC value of 14:20. I don't want it to do the conversion - I just want it to accept that my DateTime string is already in UTC.
Thanks.
Parse the string, and specify that it should assume UTC time when there is no time zone specified in the string:
DateTime clientsideProfileSyncStamp =
DateTime.Parse(
"20-May-2011 15:20:00",
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeUniversal
);
Use
DateTimeOffset.Parse
The under-advertised DateTimeOffset
type represents a point in time regardless of timezone differences, and as such should be used in preference to DateTime where a 'timestamp' is required.
@Guffa's answer is very good but i will like to add an additional answer. If your datetime string is looking like this "2017-11-27T05:30:00.000Z" then AssumeUniversal is not working. Try this :
DateTime.Parse("2017-11-27T05:30:00.000Z", null, System.Globalization.DateTimeStyles.AdjustToUniversal);
There is a slight difference between AssumeUniversal and AdjustToUniversal. Read here : Difference between AssumeUniversal and AdjustToUniversal
Add a Z
to the DateTime string:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00Z");
Console.Write(clientsideProfileSyncStamp.ToUniversalTime()); // 20-May-2011 15:20:00
Don't forget the TryParse
variant which allows you to handle a parse error without an exception
DateTime clientsideProfileSyncStamp;
DateTime.TryParse(
"20-May-2011 15:20:00",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.AssumeUniversal,
out clientsideProfileSyncStamp
);
Also if you are not using ParseExact
or TryParseExact
it will assume the output Kind
is Local
so you may also want to use ToUniversalTime()
clientsideProfileSyncStamp.ToUniversalTime();
DateTime.Parse()
or DateTime.TryParse()
var clientsideProfileSyncStamp = DateTime.Parse("20-May-2011 15:20:00");
To create culture independent DateTime use:
DateTime.Parse("2022-02-15 09:30:47", CultureInfo.InvariantCulture)
Then the date stays always exactly as defined in string.
精彩评论