欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于DateTime.ParseExact方法的使用详解

程序员文章站 2023-12-17 18:05:34
参数说明cultureinfo.currentculture获取当前线程的区域信息中,包括datetimeformat 日期显示格式(日期分隔符)和 numberforma...
参数说明
cultureinfo.currentculture获取当前线程的区域信息中,包括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。当前线程的区域信息中,日期分隔符即为-,因此,转换得以成功。
像有分割符的情况最好使用下面方式:
复制代码 代码如下:

string  temp = "1899-12-30" ;
datetimeformatinfo dtfi = new cultureinfo("zh-cn", false).datetimeformat;
datetime datetemp =  datetime.parseexact(temp "yyyy-mm-dd", dtfi, datetimestyles.none) ;  //使用当前分割符

上一篇:

下一篇: