• 如何处理DateTime日期时间格式


    如何处理DateTime日期时间格式

     

    Written by: Rickie Lee

    Dec. 12, 06

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

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

    For example, Regional OptionsTime设置:

    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 下午")

    ExceptionString 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

    Any errors or bugs, please point out. Thanks.

  • 相关阅读:
    QT下载速度慢的解决方法
    第七章 多态
    第六章 重复运用class
    第五章 隐藏实现细节
    代码改变世界
    第四章 初始化和清理
    第三章 控制程序流程
    module.exports和exports
    如何与外部源交互
    实现POST服务器
  • 原文地址:https://www.cnblogs.com/rickie/p/73701.html
Copyright © 2020-2023  润新知