基于DateTime.ParseExact方法的使用详解
时间:2021-11-15 11:33:39
参数说明
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) ; //使用当前分割符
标签:c#,DateTime.ParseExact方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#实现身份证验证功能的示例代码
2022-05-14 20:53:25
![](https://img.aspxhome.com/file/2023/6/106516_0s.png)
Java中的动态和静态编译实例详解
2021-07-30 15:25:10
简单介绍三层架构工作原理
2022-10-01 20:28:25
![](https://img.aspxhome.com/file/2023/7/98257_0s.jpg)
使用SpringMVC访问Controller接口返回400BadRequest
2023-06-05 00:14:01
Android实战打飞机游戏之怪物(敌机)类的实现(4)
2021-07-26 09:13:41
![](https://img.aspxhome.com/file/2023/2/104652_0s.gif)
Android中将View的内容保存为图像的简单实例
2023-11-01 12:45:41
Java数据结构学习之栈和队列
2022-02-21 11:32:45
![](https://img.aspxhome.com/file/2023/3/61593_0s.png)
java tostring方法重写代码示例
2022-12-31 22:38:07
spring boot补习系列之几种scope详解
2022-06-10 13:39:13
![](https://img.aspxhome.com/file/2023/0/78060_0s.png)
C#数据类型转换(显式转型、隐式转型、强制转型)
2021-11-24 13:44:25
![](https://img.aspxhome.com/file/2023/1/72461_0s.jpg)
C#简单了解接口(Interface)使用方法
2022-01-30 18:33:57
C#读写文件的方法汇总
2022-03-01 04:41:41
RestTemplate文件上传下载与大文件流式下载
2023-10-15 16:54:14
Java实现打印二叉树所有路径的方法
2021-07-13 15:52:57
![](https://img.aspxhome.com/file/2023/8/84178_0s.png)
Android使用kotlin实现多行文本上下滚动播放
2022-05-09 08:08:29
![](https://img.aspxhome.com/file/2023/6/105986_0s.gif)
Android onClick方法与setOnClickListener方法对比
2022-02-09 22:21:40
Spring项目中使用Junit单元测试并配置数据源的操作
2022-06-02 05:32:27
Android实现图片转高斯模糊以及高斯模糊布局
2023-10-20 16:10:23
Springboot过滤器禁止ip频繁访问功能实现
2022-08-29 11:20:59
Java统计输入字符的英文字母、空格、数字和其它
2022-11-13 04:11:31