您的位置:首页 > 其它

如何处理DateTime日期时间格式

2007-04-04 23:27 826 查看

如何处理DateTime日期时间格式

在.Net Framework 1.1平台下,从个人体验谈谈如何处理日期时间格式。

1. 默认情况下,DateTime.Now.ToString()的输出与Control Panel中Date/Time的设置格式相关。

For example, 当Regional Options中Time设置:

Time format: h:mm:ss tt

AM symbol: 上午

PM symbol:下午

Console.WriteLine(DateTime.Now.ToString());

输出结果:12/6/2004 2:37:37 下午

DateTime.Parse("12/6/2004 2:37:37 下午")

OK

// 将日期和时间的指定 String 表示形式转换成其等效的 SqlDateTime

SqlDateTime.Parse("12/6/2004 2:37:37 下午")

Exception:String was not recognized as a valid DateTime.

SqlDateTime.Parse("12/6/2004 2:37:37 PM")

OK

2. 通过DateTime.ToString(string format)方法,使用指定格式format将此实例的值转换成其等效的字符串表示。

DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")

输出结果:12/06/2004 14:56:37

此时,DateTime的输出格式由format参数控制,与Regional Options中的Date/Time的设置无关。不过,如果项目中有很多地方需要进行DateTime日期时间格式控制,这样写起来就比较麻烦,虽然可以通过常数const进行控制。

3. 为当前线程的区域性创建 DateTimeFormatInfo。

// Sets the CurrentCulture property to U.S. English.

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);

Console.WriteLine(DateTime.Now.ToString());

输出结果:12/6/2004 2:37:37 PM

若要为特定区域性创建 DateTimeFormatInfo,请为该区域性创建 CultureInfo 并检索 CultureInfo.DateTimeFormat 属性。

// Creates and initializes a DateTimeFormatInfo associated with the en-US culture.

DateTimeFormatInfo myDTFI = new CultureInfo( "en-US", false).DateTimeFormat;

DateTimeFormatInfo 的实例可以针对特定区域性或固定区域性创建,但不能针对非特定区域性创建。非特定区域性不提供显示正确日期格式所需的足够信息。如果试图使用非特定区域性创建 DateTimeFormatInfo 的实例,将发生异常

更详细的信息,请参考MSDN。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: