zoukankan      html  css  js  c++  java
  • csharp中DateTime总结

     

    csharp中DateTime总结

    1 时间格式输出

    DateTime的ToString(string)方法可以输出各种形式的字符串格式,总结如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace learning
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
          Test();
        }
    
        /// <summary>
        /// Description
        /// </summary>
        public void Test()
        {
          DateTime dateValue = DateTime.Now;
          // Create an array of standard format strings. 
          string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", 
                                   "R", "s", "t", "T", "u", "U", "y", ""};
          // Output date and time using each standard format string.
          StringBuilder str = new StringBuilder();
    
          foreach (string standardFmt in standardFmts)
          {
            str.Append(String.Format("{0}: {1}", standardFmt, 
                                     dateValue.ToString(standardFmt)));
            str.Append("\r\n");        
          }
          this.textBox1.Text = str.ToString();
    
          /*
          // Create an array of some custom format strings. 
          string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", 
                                 "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" };
          // Output date and time using each custom format string. 
          foreach (string customFmt in customFmts)
          {
            str.Append(String.Format("'{0}': {1}", customFmt,
                                     dateValue.ToString(customFmt)));
            str.Append("\r\n");                
          }
          this.textBox1.Text = str.ToString();
          */
       }
    
      }
    }
    /*
    d: 2013-1-18
    D: 2013年1月18日
    f: 2013年1月18日 11:33
    F: 2013年1月18日 11:33:37
    g: 2013-1-18 11:33
    G: 2013-1-18 11:33:37
    m: 1月18日
    o: 2013-01-18T11:33:37.3125000+08:00
    R: Fri, 18 Jan 2013 11:33:37 GMT
    s: 2013-01-18T11:33:37
    t: 11:33
    T: 11:33:37
    u: 2013-01-18 11:33:37Z
    U: 2013年1月18日 3:33:37
    y: 2013年1月
    : 2013-1-18 11:33:37
    
    'h:mm:ss.ff t': 11:31:22.60 上
    'd MMM yyyy': 18 一月 2013
    'HH:mm:ss.f': 11:31:22.6
    'dd MMM HH:mm:ss': 18 一月 11:31:22
    '\Mon\t\h\: M': Month: 1
    'HH:mm:ss.ffffzzz': 11:31:22.6093+08:00
    */
    

    2 求某天是星期几

    由于DayOfWeek返回的是数字的星期几,我们要把它转换成汉字方便我们阅读,有些人可能会 用switch来一个一个地对照,其实不用那么麻烦的,

    /// <summary>
    /// Description
    /// </summary>
    public void Test()
    {
      DateTime dateTime;
      dateTime = DateTime.Now;
      this.textBox1.Text = day[Convert.ToInt32(dateTime.DayOfWeek)];
    }
    string[] day = new string[]{ "星期日", "星期一", "星期二", "星期三", "星期四
          ", "星期五", "星期六" }; // }
    

    3 字符串转换为DateTime

    用DateTime.Parse(string)方法,符合"MM/dd/yyyy HH:mm:ss"格式的字符串, 如果是某些特殊格式字符串,就使用DateTime.Parse(String, IFormatProvider)方法。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Globalization;
    
    namespace learning
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
          Test();
        }
    
        /// <summary>
        /// Description
        /// </summary>
        private void ShowStr(string str)
        {
          this.textBox1.Text += str;
          this.textBox1.Text += "\r\n";               
        }
    
        /// <summary>
        /// Description
        /// </summary>
        public void Test()
        {
          // Use standard en-US date and time value
          DateTime dateValue;      
          string dateString = "2/16/2008 12:15:12 PM";
          try {
            dateValue = DateTime.Parse(dateString);
            ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
          }   
          catch (FormatException) {
            ShowStr(String.Format("Unable to convert '{0}'.", dateString));
          }
    
          // Reverse month and day to conform to the fr-FR culture.
          // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
          dateString = "16/02/2008 12:15:12";
          try {
            dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
            ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
          }   
          catch (FormatException) {
            ShowStr(String.Format("Unable to convert '{0}'.", dateString));
          }
    
          // Parse string with date but no time component.
          dateString = "2/16/2008";
          try {
             dateValue = DateTime.Parse(dateString);
             ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
          }   
          catch (FormatException) {
            ShowStr(String.Format("Unable to convert '{0}'.", dateString));
          }   
        }
      }
    }
    

    3.1 String->DateTime 的弹性做法

    利用 DateTime.ParseExact() 方法,只要你知道来源的日期格式,就可以转换。

    但是,事情往往没有那么顺利,在使用者输入内容后,从 TextBox 中取出来的字串,不见得 符合你的预期的格式,有可能字串前、中、后多了一些空白、有可能 24 小时制与 12 小时 制搞溷写错了,有可能写【AM 与 PM】而不是【上午与下午】。

    幸好 DateTime.ParseExact() 可以做到相当相当地弹性,例如:

    string[] DateTimeList = { 
                                "yyyy/M/d tt hh:mm:ss", 
                                "yyyy/MM/dd tt hh:mm:ss", 
                                "yyyy/MM/dd HH:mm:ss", 
                                "yyyy/M/d HH:mm:ss", 
                                "yyyy/M/d", 
                                "yyyy/MM/dd" 
                            }; 
    
    DateTime dt = DateTime.ParseExact(" 2008/  3/18   PM 02: 50:23  ", 
                                      DateTimeList, 
                                      CultureInfo.InvariantCulture, 
                                      DateTimeStyles.AllowWhiteSpaces
                                      ); 
    

    宣告一个 String 阵列 DateTimeList,内容值放置所有预期会客制化的日期格式,以符合各 种字串来源;使用 CultureInfo.InvariantCulture 解析各种国别不同地区设定;使用 DateTimesStyles.AllowWhiteSpaces 忽略字串一些无意义的空白。如此一来,即使像 " 2008/3 /18 PM 02: 50:23 " 这么丑陋的字串,也可以成功转到成 DateTime 型态。

    4 计算2个日期之间的天数差

    DateTime dt1 = Convert.DateTime("2007-8-1");  
    DateTime dt2 = Convert.DateTime("2007-8-15"); 
    TimeSpan span = dt2.Subtract(dt1);            
    int dayDiff = span.Days + 1; 
    

    5 求本季度第一天

    本季度第一天,很多人都会觉得这裡难点,需要写个长长的过程来判断。其实不用的,我 们都知道一年四个季度,一个季度三个月,用下面简单的方法:

    /// <summary>
    /// Description
    /// </summary>
    public void Test()
    {  
      // Use standard en-US date and time value
      DateTime dateValue = DateTime.Parse("12/12/2012");
      string str = dateValue.AddMonths(0 - ((dateValue.Month - 1) % 3)).ToString("yyyy-MM-01");
      this.textBox1.Text = str;
    }
    

    Date: 2013-01-18 15:57:28 CST

    Author: machine of awareness

    Org version 7.8.06 with Emacs version 23

    Validate XHTML 1.0
  • 相关阅读:
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业01--线性表
    C语言博客作业05--指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业02--栈和队列
    C博客作业05-指针
  • 原文地址:https://www.cnblogs.com/machine/p/2866040.html
Copyright © 2011-2022 走看看