關於c#中DateTime::ParseExact的使用說明

來源:互聯網
上載者:User

   最近碰到一個這樣的問題:我從一個控制項中擷取時間值的字串,然後把這個字串轉化成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 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.