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.

  • 相关阅读:
    Jmeter聚合报告、
    Jmeter中控件基本概念+工具使用系列(接口自动化、性能测试)
    PhpStorm创建Drupal模块项目开发教程(3)
    PhpStorm创建Drupal模块项目开发教程(2)
    PhpStorm创建Drupal模块项目开发教程
    IntelliJ IDEA 发布13版本——创造java奇迹
    图文解说PhpStorm 7.0版本新增内置工具
    图文解说PhpStorm 7.0版本语法着色
    图文解说PhpStorm 7.0版本支持PHP 5.5
    ReSharper 8.1支持TypeScript语言之代码检查特征
  • 原文地址:https://www.cnblogs.com/rickie/p/73701.html
Copyright © 2011-2022 走看看