关于c#中DateTime::ParseExact的使用说明
来源:互联网 发布:优酷录视频软件 编辑:程序博客网 时间:2024/05/29 07:33
最近碰到一个这样的问题:我从一个控件中获取时间值的字符串,然后把这个字符串转化成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
- 关于c#中DateTime::ParseExact的使用说明
- C# DateTime的 ParseExact和 TryParseExact 使用说明
- DateTime.ParseExact的使用
- C# DateTime.ParseExact 使用学习
- 基于DateTime.ParseExact方法的使用详解
- DateTime.ParseExact方法
- DateTime.ParseExact 函数
- C#中datetime的使用
- C#中datetime的使用
- C#中datetime的使用
- C#中datetime的使用
- C#中datetime的使用
- c# 中datetime的问题
- C#中datetime的使用
- C# 关于readonly的使用说明
- 关于Json中DateTime类型与.Net DateTime的转化
- C#中DateTime类型的使用
- C#中对于DateTime的介绍
- 使用JavaScript控制重复提交
- 关于jsp页面之间传值的中文乱码总结
- How to move the databases that are used by SharePoint Portal Server 2003 to a computer that is running SQL Server
- 利用.NET进行预览和打印
- about Microsoft Office SharePoint Portal Server 2003
- 关于c#中DateTime::ParseExact的使用说明
- 《The Art of Assembly Language》中文名:汇编语言编程艺术 中英文正式版本下载
- 搜索引擎重复网页发现技术分析
- [程序员必看]请不要做浮躁的人
- 程序设计有技巧
- 如何才能做好一个垂直搜索引擎
- 接触WAP_WML的一些总结[不断补充]
- 如何提高GIS应用系统的运行速度
- java面试笔试题大汇总 及c/c++面试试题(转载 )