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.

  • 相关阅读:
    【转】为什么要报考系统架构设计师考试
    前端三大主流框架中文文档
    零散知识点-类的区别;函数式编程的简单总结;
    window.location相关方法
    Hybrid相关
    php中file_get_contents与curl的区别
    三级下拉菜单
    微信生成带参数二维码及响应操作
    开发中因长时间不用而遗忘的,持续补充中。。
    项目中用到的几个工具函数
  • 原文地址:https://www.cnblogs.com/rickie/p/73701.html
Copyright © 2011-2022 走看看