解析日期像“2010年1月13日星期三”与.NET [英] Parsing a Date Like "Wednesday 13th January 2010" with .NET

查看:113
本文介绍了解析日期像“2010年1月13日星期三”与.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下字符串转换为System.DateTime对象?

How can I convert the following strings to a System.DateTime object?

2010年1月13日星期三

2010年1月21日星期四

2010年2月3日星期三

Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010

通常情况如下:

DateTime dt;
DateTime.TryParseExact(value, "dddd d MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);

但是由于th,st或rd字符串

but this doesn't work because of the 'th', 'st' or 'rd' in the string

更新

看起来DateTime 不支持格式化'th','st','rd'等,所以他们需要在解析前被剥离。 Rubens Farias提供了一个很好的正则表达式。

It appears that DateTime doesn't support formatting the 'th', 'st', 'rd' etc so they need to be stripped before parsing. Rubens Farias provides a nice regular expression below.

推荐答案

如何剥离他们?

string value = "Wednesday 13th January 2010";
DateTime dt;
DateTime.TryParseExact(
    Regex.Replace(value, @"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
    "dddd d MMMM yyyy", 
    DateTimeFormatInfo.InvariantInfo, 
    DateTimeStyles.None, out dt);

这篇关于解析日期像“2010年1月13日星期三”与.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆