使用精确解析转换英文日期
Convert english Date with parse exact
我尝试将英文日期转换为德文日期,但格式不正确。
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime currentCultureDate = DateTime.Now;
string format = "dd.MM.yyyy HH:mm:ss";
Console.WriteLine("Format: " + format);
Console.WriteLine("Original Date: " + currentCultureDate);
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
Console.WriteLine("Converted Date: " + convertedDate);
格式异常......
DateTime.ParseExact
用于从 string
创建 DateTime
。您可以传递一个 DateTimeFormat
或 CultureInfo
用于将该字符串转换为 DateTime
.
方法 不会 将其转换为另一个 CultureInfo
中的 string
,比如 de-DE
。因此你可以使用 DateTime.ToString
:
string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE"));
你没有按照你说的去做:你的代码实际上试图解析德语格式的日期:
// This is German format
string format = "dd.MM.yyyy HH:mm:ss";
// This takes a date and parses it using the ABOVE FORMAT - which is German
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
如果你已经有一个DateTime
你想输出德语格式,你不需要ParseExact
,但是ToString
:
string german = DateTime.Now.ToString(format, new CultureInfo("de-DE"));
A DateTime
本身没有附加任何文化格式。这只是一个日期和时间。只有当您 输出 一个 DateTime
时,它才需要以某种方式转换为字符串,为此,需要文化信息。所以经验法则是:
- 如果你得到一个表示日期和时间值的字符串,你需要将它解析为
DateTime
,要么使用固定格式,要么[=13] =] 或依赖框架,将源文化信息传递给 Parse
或 TryParse
.
- 如果你有一个
DateTime
并且想要 输出 它,你需要使用 ToString
来格式化它,提供固定的格式字符串和文化信息,或仅对当前线程的文化使用 ToString
。
我尝试将英文日期转换为德文日期,但格式不正确。
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime currentCultureDate = DateTime.Now;
string format = "dd.MM.yyyy HH:mm:ss";
Console.WriteLine("Format: " + format);
Console.WriteLine("Original Date: " + currentCultureDate);
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
Console.WriteLine("Converted Date: " + convertedDate);
格式异常......
DateTime.ParseExact
用于从 string
创建 DateTime
。您可以传递一个 DateTimeFormat
或 CultureInfo
用于将该字符串转换为 DateTime
.
方法 不会 将其转换为另一个 CultureInfo
中的 string
,比如 de-DE
。因此你可以使用 DateTime.ToString
:
string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE"));
你没有按照你说的去做:你的代码实际上试图解析德语格式的日期:
// This is German format
string format = "dd.MM.yyyy HH:mm:ss";
// This takes a date and parses it using the ABOVE FORMAT - which is German
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
如果你已经有一个DateTime
你想输出德语格式,你不需要ParseExact
,但是ToString
:
string german = DateTime.Now.ToString(format, new CultureInfo("de-DE"));
A DateTime
本身没有附加任何文化格式。这只是一个日期和时间。只有当您 输出 一个 DateTime
时,它才需要以某种方式转换为字符串,为此,需要文化信息。所以经验法则是:
- 如果你得到一个表示日期和时间值的字符串,你需要将它解析为
DateTime
,要么使用固定格式,要么[=13] =] 或依赖框架,将源文化信息传递给Parse
或TryParse
. - 如果你有一个
DateTime
并且想要 输出 它,你需要使用ToString
来格式化它,提供固定的格式字符串和文化信息,或仅对当前线程的文化使用ToString
。