关于c#中DateTime::ParseExact的使用说明

来源:互联网 发布:优酷录视频软件 编辑:程序博客网 时间:2024/05/29 07:33


   最近碰到一个这样的问题:我从一个控件中获取时间值的字符串,然后把这个字符串转化成DateTime对象,在控件中显示的时间值是: 2005-06-07 12:23:34分,但是我通过一个函数去获取这个值后,得到的是2005-6-7 12:23:34,因此当设置时间格式为: yyyy-MM-dd HH:mm:ss 去调用DateTime::ParseExact函数的时候就出现了异常,提示是时间格式不匹配。这就提醒我们,在设定时间格式后,调用DateTime::ParseExact去把一个字符串转成DateTime对象,必须保证这个字符串的格式和我们设定的要转换的时间格式一致,否则就会有异常。

//下面这段程序就会出现异常,异常提示为:字符串未被识别为有效的DateTime.
using  System.Globalization;
namespace _3
{
 class Class1
 {
  static void Main(string[] args)
  {
   string mytime = "2005-6-7 12:23:34";
   IFormatProvider culture = new CultureInfo("zh-CN", true);
     //期望的时间格式为月,日必须为两位,不足两位,左边应该填0补充
   string[] expectedFormats = {"yyyy-MM-dd HH:mm:ss"};
   DateTime dt =
    DateTime.ParseExact(mytime,
    expectedFormats,
    culture,
    DateTimeStyles.AllowInnerWhite);
   Console.WriteLine("dt = {0}", dt);
  }
 }
}

改正的方法有两个:
1. string mytime = "2005-6-7 12:23:34"; 改为: string mytime = "2005-06-07 12:23:34";
2. 期望的格式从string[] expectedFormats = {"yyyy-MM-dd HH:mm:ss"}; 改为: string[] expectedFormats = {"yyyy-M-d HH:mm:ss"};


//下面这段代码可以匹配毫秒.
using  System;
using  System.Globalization;
namespace _3
{
 class Class1
 {
  static void Main(string[] args)
  {
   string mytime = "2005-6-7 12:23:34.123";
   IFormatProvider culture = new CultureInfo("zh-CN", true);
   string[] expectedFormats = {"yyyy-M-d HH:mm:ss.fff"};
   DateTime dt =
    DateTime.ParseExact(mytime,
    expectedFormats,
    culture,
    DateTimeStyles.AllowInnerWhite);
   Console.WriteLine("dt = {0},毫秒: {1} ", dt,dt.Millisecond);
  }
 }
}
输出的结果为: dt = 2005-6-7 12:23:34 ,毫秒: 123