将本地化字符串转换为日期时间

Converting a localized string to datetime

我想将本地化字符串(最好是任何受支持的语言)转换为日期时间对象。 字符串例如(荷兰语):woensdag 3 juni 2015 9:12:14 uur CEST

本地化字符串始终采用相同格式:[日名称] [日] [月] [年] [小时] [分钟] [秒] [小时的字面意思] [时区] 无法在主机应用程序上更改提供给程序的字符串(权限不足)。

我读到在 C# .NET 中我需要使用类似 InvariantCulture 对象的东西来将 DateTime 对象更改为本地化的字符串日期。

但是有可能反过来吗?如果可以,是否可以满足我的上述要求?

提前感谢您的帮助!

由于提出的原始问题下方的评论,我已经设法解决了这个问题。

通过使用字符串替换,我可以放弃本地化的 'uur',后者在荷兰语中代表小时以及 CEST。

下面的代码对我有用:

CultureInfo nlculture = new CultureInfo("nl-NL");
string test = "woensdag 3 juni 2015 9:12:14";
DateTime dt = DateTime.ParseExact(test, "dddd d MMMM yyyy H:mm:ss", nlculture);
System.Windows.MessageBox.Show(dt.ToString());

回到要求之一,即让它支持多种语言。我可以(在再次检查我可以使用的东西之后)捕获使用的语言,从而让我能够支持多种语言。

感谢大家的帮助

首先,DateTime是时区意识。它没有 任何 有关时区的信息。这就是为什么您需要将此 CEST 部分解析为文字定界符的原因。 (AFAIK,除了转义之外没有办法解析它们)看起来 uur 在英语中表示 "hour",您需要将其指定为文字嗯。

然后,您可以将其解析为 dddd d MMMM yyyy H:mm:ss 'uur CEST'" 格式和 nl-BE 文化之类的字符串;

string s = "woensdag 3 juni 2015 9:12:14 uur CEST";
DateTime dt;
if(DateTime.TryParseExact(s, "dddd d MMMM yyyy H:mm:ss 'uur CEST'", 
                          CultureInfo.GetCultureInfo("nl-BE"),
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt); // 03/06/2015 09:12:14
}

肯定不想使用InvariantCulture来解析这个字符串。这种文化是基于英语的,并保留DayNames他们的英文名字,如星期三等。

顺便说一下,Nodatime 有 ZonedDateTime structure and looks like it supports a time zone with it's Zone property.

下面的代码应该可以工作。我收到一个错误,但我认为这是由于我的计算机上安装了旧版本的 VS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;


namespace ConsoleApplication53
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime x = DateTime.ParseExact("3 june 2015 9:12:14 PM GMT", "d MMMM yyyy h:mm:ss tt Z", CultureInfo.InvariantCulture);
            string y = x.ToString("d MMMM yyyy h:mm:ss tt K", CultureInfo.CreateSpecificCulture("nl-NL"));
            string dutchTimeString = "3 juni 2015 9:12:14 uur CEST";

            DateTime date = DateTime.ParseExact(dutchTimeString, "d MMMM yyyy h:mm:ss tt Z", CultureInfo.CreateSpecificCulture("nl-BE"));

        }

    }
}