软件编程
位置:首页>> 软件编程>> C#编程>> 使用DateTime的ParseExact方法实现特殊日期时间的方法详解

使用DateTime的ParseExact方法实现特殊日期时间的方法详解

  发布时间:2021-10-06 01:48:54 

标签:DateTime,ParseExact方法,特殊日期时间

今天遇到一个特别的需求,需要从下面的字符串中转换成一个DateTime对象:


[07-13 15:50:42]


主要问题是这个时间不是标准的时间,而是自定义的格式,即开头是月-日,然后是时间。
使用最常用的DateTime.Parse(string dateTimeStr)无法转换,问题就在于这个自定义格式上。
搜索了之后,我找到了下面的方法:


public static DateTime ParseExact(
 string s,
 string format,
 IFormatProvider provider
)


使用例子如下:


var dateTimeStr = "07-13 15:50:42";
var dateTime = DateTime.ParseExact(dateTimeStr, "MM-dd HH:mm:ss", CultureInfo.InvariantCulture);


使用效果如下:

使用DateTime的ParseExact方法实现特殊日期时间的方法详解

如果你使用的其它特殊语言,比如美国或者日文啥的,最后的参数你可能需要获取下对应的Culture。
注意:
•如果dateTimeStr或者format 是null,会抛出ArgumentNullException异常。
•如果dateTimeStr或者format 是空字符串,则抛出FormatException异常。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com