zoukankan      html  css  js  c++  java
  • 如何处理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.

  • 相关阅读:
    SonarQube 之 权限模板配置
    window jenkins + sonarqube + sonar-scanner 最佳实践
    到某个指定的页面不可以后退
    php里面判断是pc还是手机
    爱奇艺视频引入
    给电脑安装字体
    应用宝下线
    ps 如何的复制想要的东西,以及修改
    实现倒计时的效果(3秒倒计时)
    数据库里的数据被删除,依然想按照顺序往下递增的解决办法
  • 原文地址:https://www.cnblogs.com/rickie/p/73701.html
Copyright © 2011-2022 走看看