基于DateTime.ParseExact方法的使用詳解
更新時間:2013年05月18日 10:10:15 作者:
本篇文章是對DateTime.ParseExact方法的使用進行了詳細的分析介紹,需要的朋友參考下
參數說明
CultureInfo.CurrentCulture獲取當前線程的區(qū)域信息中,包括DateTimeFormat 日期顯示格式(日期分隔符)和 NumberFormat 貨幣。
試例:
1、時間中沒有使用分割符的情況:
string temp = "18991230" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None);
2、時間中使用分割符的情況:
string temp = "1899-12-30" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy/MM/dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
都正確,原因:
CultureInfo.CurrentCulture獲取當前線程的CultureInfo的DateTimeFormat屬性作為IFormatProvider,然后在DateTimeParse.ParseByFormat方法中,遇到format參數的/字符時,會比較輸入日期字符串的當前字符是否為當前DateTimeFormatInfo的DateSeperator,如果是,則返回true,即允許轉換,如果不是則返回false。當前線程的區(qū)域信息中,日期分隔符即為-,因此,轉換得以成功。
像有分割符的情況最好使用下面方式:
string temp = "1899-12-30" ;
DateTimeFormatInfo dtfi = new CultureInfo("zh-CN", false).DateTimeFormat;
DateTime dateTemp = DateTime.ParseExact(temp "yyyy-MM-dd", dtfi, DateTimeStyles.None) ; //使用當前分割符
CultureInfo.CurrentCulture獲取當前線程的區(qū)域信息中,包括DateTimeFormat 日期顯示格式(日期分隔符)和 NumberFormat 貨幣。
試例:
1、時間中沒有使用分割符的情況:
復制代碼 代碼如下:
string temp = "18991230" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None);
2、時間中使用分割符的情況:
復制代碼 代碼如下:
string temp = "1899-12-30" ;
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
DateTime dateTemp = DateTime.ParseExact(temp, "yyyy/MM/dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
都正確,原因:
CultureInfo.CurrentCulture獲取當前線程的CultureInfo的DateTimeFormat屬性作為IFormatProvider,然后在DateTimeParse.ParseByFormat方法中,遇到format參數的/字符時,會比較輸入日期字符串的當前字符是否為當前DateTimeFormatInfo的DateSeperator,如果是,則返回true,即允許轉換,如果不是則返回false。當前線程的區(qū)域信息中,日期分隔符即為-,因此,轉換得以成功。
像有分割符的情況最好使用下面方式:
復制代碼 代碼如下:
string temp = "1899-12-30" ;
DateTimeFormatInfo dtfi = new CultureInfo("zh-CN", false).DateTimeFormat;
DateTime dateTemp = DateTime.ParseExact(temp "yyyy-MM-dd", dtfi, DateTimeStyles.None) ; //使用當前分割符
您可能感興趣的文章:
- C#中DateTime日期類型格式化顯示方法匯總
- c#詳解datetime使用示例
- c#友好顯示日期 c#日期datetime使用方法
- c# datetime 格式化大全
- c# DateTime常用操作實例(datetime計算時間差)
- 深入Unix時間戳與C# DateTime時間類型互換的詳解
- 使用DateTime的ParseExact方法實現特殊日期時間的方法詳解
- c#中DateTime.Now函數的使用詳解
- asp.net利用cookie保存用戶密碼實現自動登錄的方法
- asp.net中button控制先執(zhí)行js再執(zhí)行后臺程序的方法
- .NET的DateTime函數獲取上個月的起始和截止時間的方法
相關文章
小白2分鐘學會Visual Studio如何將引用包打包到NuGet上
這篇文章主要介紹了小白2分鐘學會Visual Studio如何將引用包打包到NuGet上,只需兩步完成打包上傳操作,需要的朋友可以參考下2021-09-09

