简体   繁体   English

ParseExact没有解析字符串的日期,日期与序数但没有年份

[英]ParseExact not parsing string with day, date with ordinal but no year

I have reviewed the answer to Parse very long date format to DateTime in C# and it goes a little way to fixing my problem, but I fear I might be stumbling into an unrelated issue, and thus have opened this new thread. 我已经回顾了在C#中将非常长的日期格式解析为DateTime的答案,并且它解决了我的问题,但我担心我可能会遇到一个无关的问题,因此打开了这个新线程。

Dates come into my process as a string that I have no control over. 日期作为一个我无法控制的字符串进入我的过程。 They always represent a date in the future. 它们总是代表未来的日期。 An example would be " Wednesday 26th November at 18:30 ". 一个例子是“ Wednesday 26th November at 18:30 ”。 Notice, the day has an ordinal, and that there is no year. 注意,这一天有一个序数,而且没有一年。

I need to get these into a DateTime structure, so that I can... well, do DateTime things to them! 我需要把它们变成一个DateTime结构,这样我就可以......好吧,给它们做DateTime事情吧!

I am currently using the following snippet (adjusted from the afore mentioned question), but it's still failing on the last conditional, which I would expect it to pass. 我目前正在使用以下片段(根据前面提到的问题进行调整),但它仍然在最后一个条件失败,我希望它能通过。

public DateTime ParseOrdinalDateTime(string dt)
{
    DateTime d;
    if (DateTime.TryParseExact(dt, "dddd d\"st\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
        return d;
    if (DateTime.TryParseExact(dt, "dddd d\"nd\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
        return d;
    if (DateTime.TryParseExact(dt, "dddd d\"rd\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
        return d;
    if (DateTime.TryParseExact(dt, "dddd d\"th\" MMMM \"at\" hh:mm", null, DateTimeStyles.AssumeLocal, out d))
        return d;

    throw new InvalidOperationException("Not a valid DateTime string");
}

如果您正在接收24小时格式化时间,那么您应该将字符串解析为"dddd d\\"th\\" MMMM \\"at\\" HH:mm" (注意大写的Hs)。

1) Swap the hh:mm to HH:mm (using 24 hours..) 1)将hh:mm换成HH:mm(使用24小时..)
2) Set culture to en-US 2)将文化设置为en-US

Such as

 string dateString = "Wednesday 26th November at 18:30"; string format = "dddd d\\"th\\" MMMM \\"at\\" HH:mm"; DateTime dt; DateTime.TryParseExact(dateString, format, new CultureInfo("en-US"), DateTimeStyles.AssumeLocal, out dt); 

edit - formatted 编辑 - 格式化

Your format string is a little bit off and you need to set a culture: 您的格式字符串有点偏离,您需要设置文化:

private static void Main(string[] args)
{
    DateTime result = ParseOrdinalDateTime("Friday 29th August at 18:30");
}

public static DateTime ParseOrdinalDateTime(string dt)
{
    DateTime d;

    if (DateTime.TryParseExact(dt, "dddd d\"th\" MMMM \"at\" HH:mm",  CultureInfo.CreateSpecificCulture("en-GB"), DateTimeStyles.AssumeLocal, out d))
    {
        return d;
    }

    throw new InvalidOperationException("Not a valid DateTime string");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM