c#美味:用DateTime的ParseExact方法解析特殊的日期時間

來源:互聯網
上載者:User
文章目錄
  •  
  • 參考資料

今天遇到一個特別的需求,需要從下面的字串中轉換成一個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);

使用效果如下:

如果你使用的其它特殊語言,比如美國或者日文啥的,最後的參數你可能需要擷取下對應的Culture。

注意:

  • 如果dateTimeStr或者format 是null,會拋出ArgumentNullException異常。
  • 如果dateTimeStr或者format 是Null 字元串,則拋出FormatException異常。
 參考資料

DateTime.ParseExact Method (String, String, IFormatProvider)

http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.