C# 時間與字符串類型的相互格式化轉換


以下這第一部分是來自網絡,基本也都是對的。可以參考着用。

哎~~哎,別急着關,再往下看看

時間格式化輸出:
     Label1.Text = dt.ToString();//2005-11-5 13:21:25
       Label2.Text = dt.ToFileTime().ToString();//127756416859912816
       Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
       Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
       Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
     Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
       Label7.Text = dt.ToOADate().ToString();//38661.5565508218
       Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
       Label9.Text = dt.ToShortTimeString().ToString();//13:21
       Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25  2005-11-5 13:30:28.4412864
       Label1.Text = dt.Year.ToString();//2005
       Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
       Label3.Text = dt.DayOfWeek.ToString();//Saturday
       Label4.Text = dt.DayOfYear.ToString();//309
       Label5.Text = dt.Hour.ToString();//13
       Label6.Text = dt.Millisecond.ToString();//441
       Label7.Text = dt.Minute.ToString();//30
       Label8.Text = dt.Month.ToString();//11
       Label9.Text = dt.Second.ToString();//28
       Label10.Text = dt.Ticks.ToString();//632667942284412864
       Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
       Label1.Text = dt.ToString();//2005-11-5 13:47:04
       Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
       Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
       Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
       Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
       Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
       Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
       Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
       Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
       Label10.Text = dt.CompareTo(dt).ToString();//0
       Label11.Text = dt.Add(?).ToString();//問號為一個時間段
       Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
       Label2.Text = dt.Equals(dt).ToString();//True
       Label3.Text = dt.GetHashCode().ToString();//1474088234
       Label4.Text = dt.GetType().ToString();//System.DateTime
       Label5.Text = dt.GetTypeCode().ToString();//DateTime

       Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
       Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
       Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
     Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
     Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
       Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
       Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
     Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
     Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
       Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
       Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMTv 
=================================================

1.DateTime.Parse(str);
2.DateTime dt = DateTime.Now;
   DateTime.TryParse(str,out dt);
3.Convert.ToDateTime(str);

1.直接強轉,如果轉換過程有異常將會拋出異常,否則返回轉換后的結構。
2.先創建一個DateTime對象,如果有異常,返回值將是dt創建時候的值,如果沒異常,會把轉換后的結果賦給dt。
3.也是直接強轉,如果轉換過程有異常將會拋出異常,否則返回轉換后的結構。與1的區別就是,它能接受的參數類型更多。

 

----------------------------------------我是分割線---------------------------------

 

首先我們先看一段MSDN的示例代碼,它對日期的一些樣式設置做了簡單示例。

using System;
using System.Globalization;


public class SamplesCultureInfo  {

   public static void Main()  {

      // Creates and initializes a CultureInfo.
      CultureInfo myCI = new CultureInfo("en-US", false);

      // Clones myCI and modifies the DTFI and NFI instances associated with the clone.
      CultureInfo myCIclone = (CultureInfo) myCI.Clone();
      myCIclone.DateTimeFormat.AMDesignator = "a.m.";
      myCIclone.DateTimeFormat.DateSeparator = "-";
      myCIclone.NumberFormat.CurrencySymbol = "USD";
      myCIclone.NumberFormat.NumberDecimalDigits = 4;

      // Displays the properties of the DTFI and NFI instances associated with the original and with the clone. 
      Console.WriteLine( "DTFI/NFI PROPERTY\tORIGINAL\tMODIFIED CLONE" );
      Console.WriteLine( "DTFI.AMDesignator\t{0}\t\t{1}", myCI.DateTimeFormat.AMDesignator, myCIclone.DateTimeFormat.AMDesignator );
      Console.WriteLine( "DTFI.DateSeparator\t{0}\t\t{1}", myCI.DateTimeFormat.DateSeparator, myCIclone.DateTimeFormat.DateSeparator );
      Console.WriteLine( "NFI.CurrencySymbol\t{0}\t\t{1}", myCI.NumberFormat.CurrencySymbol, myCIclone.NumberFormat.CurrencySymbol );
      Console.WriteLine( "NFI.NumberDecimalDigits\t{0}\t\t{1}", myCI.NumberFormat.NumberDecimalDigits, myCIclone.NumberFormat.NumberDecimalDigits );

   }

}

/*
This code produces the following output.

DTFI/NFI PROPERTY       ORIGINAL        MODIFIED CLONE
DTFI.AMDesignator       AM              a.m.
DTFI.DateSeparator      /               -
NFI.CurrencySymbol      $               USD
NFI.NumberDecimalDigits 2               4

*/


就是說,我們可以通過System.Globalization.CultureInfo類,對日期的格式化轉換輸出做出設定。

所以,當我把代碼改成這樣時:

//記得 using System.Globalization;

// Creates and initializes a CultureInfo.
            CultureInfo myCI = new CultureInfo("en-US", false);

            // Clones myCI and modifies the DTFI and NFI instances associated with the clone.
            CultureInfo myCIclone = (CultureInfo)myCI.Clone();
            myCIclone.DateTimeFormat.AMDesignator = "a.m.";
            myCIclone.DateTimeFormat.PMDesignator = "P.M.";
            myCIclone.DateTimeFormat.DateSeparator = ".";
            myCIclone.NumberFormat.CurrencySymbol = "USD";
            myCIclone.NumberFormat.NumberDecimalDigits = 4;

            // Displays the properties of the DTFI and NFI instances associated with the original and with the clone. 
            Console.WriteLine("DTFI/NFI PROPERTY\tORIGINAL\tMODIFIED CLONE");
            Console.WriteLine("DTFI.AMDesignator\t{0}\t\t{1}", myCI.DateTimeFormat.AMDesignator, myCIclone.DateTimeFormat.AMDesignator);
            Console.WriteLine("DTFI.DateSeparator\t{0}\t\t{1}", myCI.DateTimeFormat.DateSeparator, myCIclone.DateTimeFormat.DateSeparator);
            Console.WriteLine("NFI.CurrencySymbol\t{0}\t\t{1}", myCI.NumberFormat.CurrencySymbol, myCIclone.NumberFormat.CurrencySymbol);
            Console.WriteLine("NFI.NumberDecimalDigits\t{0}\t\t{1}", myCI.NumberFormat.NumberDecimalDigits, myCIclone.NumberFormat.NumberDecimalDigits);

            Console.WriteLine(DateTime.Now.ToString(myCIclone));

輸出是:
DTFI/NFI PROPERTY       ORIGINAL        MODIFIED CLONE
DTFI.AMDesignator       AM              a.m.
DTFI.DateSeparator      /               .
NFI.CurrencySymbol      $               USD
NFI.NumberDecimalDigits 2               4
5.19.2013 12:18:44 a.m.

----------------------------

紅色字部分是當前日期時間,也就是我寫這篇文章的時間了。

表示早晨的“AM”改成了“a.m.”,而我們習慣的yyyy-MM-dd格式中的“-”或者系統通常默認設置的“/”分隔符被我改成了“.”。

好吧。我們繼續往下走。

我的主要目的是改日期時間格式,從上文示例中可以看出來,我們應該操作的就是DateTimeFormat中的設置了。

恰好,DateTimeFormat對應有一個類,其繼承結構是: System.Globalization.DateTimeFormatInfo

接下來的問題就很簡單了,直接簡單粗暴的上一段代碼:

System.Globalization.DateTimeFormatInfo fi = new System.Globalization.DateTimeFormatInfo();            
fi.FullDateTimePattern="yyyy年MM月dd日 的 HH時mm分ss秒";
Console.WriteLine("{0}", DateTime.Now.ToString(fi.FullDateTimePattern));

結果是這樣的:2013年05月19日 的 00時18分44秒

當然,你也可以更粗暴的:

Console.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 的 HH時mm分ss秒"));

結果是一樣的。

但我在示例中用的是全格式日期時間FullDateTimePattern,DateTimeFormatInfo還有很多其它的設置,靈活性更強一點。

具體請看MSDN:http://msdn.microsoft.com/zh-cn/library/system.globalization.datetimeformatinfo(v=vs.100).aspx

 

說完時間轉字符串的,接着說說字符串轉時間的。

 我們在處理字符串(string類型)轉日期類型(DateTime)時常用DateTime.Pares() ,但如果在處理舊有特殊時間字符串數據的時候,如何轉換成時間類型呢,例如

//分別獲取20051126中的年、月、日字符串
string   yyyy= "20051126 ".Substring(0,4);
string   mm= "20051126 ".Substring(4,2);
string   dd= "20051126 ".Substring(5,2);

//拼寫符合日期格式的字符串
string   riqi=yyyy+ "- "+mm+ "- "+dd;

//將符合日期格式的字符串轉化為DateTime數據類型
DateTime   dt=Convert.ToDateTime(riqi);
DateTime dt = DateTime.Parse(str);


//但是這個形式的轉換是相當有限的,有些C#是會不懂你寫入的日期格式的如20100427140027
//大家都明白是2010-04-27 可以C#不認識他.我們可以這樣子進行如下
string strDateFormat = "yyyyMMddHHmmss";
string date = "20100427140027";
DateTime convertTime = DateTime.ParseExact(date, strDateFormat, new System.Globalization.CultureInfo("zh-CN"), System.Globalization.DateTimeStyles.AllowWhiteSpaces);
Console.Write(string.Format("{0}", convertTime.ToString()));

//輸出:2010-04-27 14:00:27

我們再改改

string strDateFormat = "yyyy年MM月dd日 的 HH時mm分ss秒"; 
string date = "2089年05月19日 的 23時49分23秒";
DateTime convertTime = DateTime.ParseExact(date, strDateFormat, new System.Globalization.CultureInfo("zh-CN"), System.Globalization.DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine(string.Format("{0}", convertTime.ToString()));

輸出:2089-05-19 23:49:23

 

文筆不好,但希望內容對您有幫助。

 


免責聲明!

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



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