DateTime conversion regardless of culture

2019-09-01 01:22发布

I have a text string that needs to become a DateTime object:

Feb 10, 2012 at 16:33.29

This text does not change, but the software will run on many different devices with different DateTime formats.

How can I set a custom DateTime parser so that regardless of culture I will get a fully populated DateTimeobject?

4条回答
放荡不羁爱自由
2楼-- · 2019-09-01 01:27

parse with CultureInfo.InvariantCulture?

查看更多
欢心
3楼-- · 2019-09-01 01:35

Use ParseExact with a custom format string and the invariant culture:

DateTime date = DateTime.ParseExact(theString, "MMM d', 'yyyy' at 'HH':'mm'.'ss", CultureInfo.InvariantCulture);
查看更多
The star\"
4楼-- · 2019-09-01 01:49

Here’s a custom format to match your example:

var dt = DateTime.ParseExact(
    "Feb 10, 2012 at 16:33.29", 
    "MMM d, yyyy 'at' HH:mm.ss", 
    CultureInfo.InvariantCulture);
查看更多
Lonely孤独者°
5楼-- · 2019-09-01 01:49

One thing has got nothing to do with the other.

DateTime.Parse(value, formatstr) returns a DateTime.

The DateTime does not have a format, unless you want to talk about how it's represented in memory. When you convert it to a string, you generally do it with an implicit or explicit format, once you have it is no longer a datetime...

查看更多
登录 后发表回答