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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM