格式化特定文化特性的日期和時間

更新:2007 年 11 月

DateTime 結構提供方法,可讓您的應用程式對 DateTime 型別執行不區分文化特性的作業。應用程式可以使用 DateTimeFormatInfo 類別根據文化特性來格式化和顯示 DateTime 型別。例如,使用 ShortDatePattern 時,2001 年 2 月 1 日這個日期可格式化為英文 (美國) "en-US" 文化特性的 2/1/2001,以及格式化為英文 (英國) "en-GB" 文化特性的 01/02/2001。

DateTimeFormatInfo 物件可以為特定文化特性或不因文化特性而異 (Invariant Culture) 建立,但不可為中性文化特性建立。中性文化特性並未提供足夠的資訊來顯示正確的日期格式。如果應用程式嘗試使用中性文化特性來建立 DateTimeFormatInfo 物件,將會擲回例外狀況。如需其他資訊和使用 DateTime 格式的範例,請參閱日期和時間格式字串

下列程式碼範例在 CurrentThread 目前文化特性設為英文 (美國) "en-US",然後設為德文 (德國) "de-DE" 時,使用 ShortDatePattern 顯示目前日期。

Imports System
Imports System.Globalization
Imports System.Threading

Public Class FormatDate
   
   Public Shared Sub Main()
      Dim dt As DateTime = DateTime.Now
      ' Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      ' Displays dt, formatted using the ShortDatePattern
      ' and the CurrentThread.CurrentCulture.
      Console.WriteLine(dt.ToString("d"))
      
      ' Creates a CultureInfo for German in Germany.
      Dim ci As New CultureInfo("de-DE")
      ' Displays dt, formatted using the ShortDatePattern
      ' and the CultureInfo.
      Console.WriteLine(dt.ToString("d", ci))
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class FormatDate
{
   public static void Main()
   {
      DateTime dt = DateTime.Now;
      // Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Displays dt, formatted using the ShortDatePattern
      // and the CurrentThread.CurrentCulture.
      Console.WriteLine(dt.ToString("d"));
      
      // Creates a CultureInfo for German in Germany.
      CultureInfo ci = new CultureInfo("de-DE");
      // Displays dt, formatted using the ShortDatePattern
      // and the CultureInfo.
      Console.WriteLine(dt.ToString("d", ci));
   }
}

如果您在 2001 年 7 月 9 日執行這個執行碼,它將產生下列輸出:

7/9/2001
09.07.2001

使用時區

DateTime 結構一律使用當地的時區來進行計算和比對。當您的應用程式使用 Parse() 和 ParseExact() 方法時,請將此點列入考量。這些方法提供多載,可將日期和時間的字串表示轉換成 DateTime 型別。您的應用程式也可以針對特定文化特性格式化 DateTime。如果傳遞到這些方法的字串中沒有指定時區,它們會擷取剖析的日期和時間,而不執行時區調整。該日期和時間將依據作業系統的時區設定而來。如果應用程式指定時區位移,這些方法將會剖析日期/時間字串,接著將它轉換成 Coordinated Universal Time (UTC;先前稱為 Greenwich Mean Time 或 GMT),最後再將它轉換成當地系統時間。

應用程式應使用 ToUniversalTime 方法來轉換當地 DateTime 型別到其對等的 UTC。若要剖析日期/時間字串並將之轉換為 UTC DateTime 型別,應用程式應搭配使用 DateTimeStyles 列舉型別 AdjustToUniversal 值與 Parse() 方法或 ParseExact() 方法。

下列程式碼範例會為當地時間建立 DateTime 型別,然後將它轉換成對等的 UTC。這兩種型別都會轉換成字串並寫入主控台中。請注意,該字串會因當地時間時區與 UTC 之間的 UTC 位移而有所不同。這些字串將使用 ParseExact() 方法轉換回 DateTime 型別。若要擷取儲存在 utcdt 中的時區資訊,DateTimeStyles 的 AdjustToUniversal 值必須指定為 ParseExact 方法的參數。如需不同時區的 UTC 位移的詳細資訊,請參閱 GetUtcOffset

Imports System
Imports System.Globalization
Imports System.Threading

Public Class TimeZoneSample
   Public Shared Sub Main()
      Dim en As New CultureInfo("en-US")
      Thread.CurrentThread.CurrentCulture = en

      ' Creates a DateTime for the local time.
      Dim dt As New DateTime(2001, 7, 13, 4, 0, 0)

      ' Converts the local DateTime to the UTC time.
      Dim utcdt As DateTime = dt.ToUniversalTime()

      ' Defines a custom string format to display the DateTime.
      ' zzz specifies the full time zone offset.
      Dim format As [String] = "MM/dd/yyyy hh:mm:sszzz"

      ' Converts the local time to a string
      ' using the custom format string and display.
      Dim str As [String] = dt.ToString(format)
      Console.WriteLine(str)

      ' Converts the UTC time to a string
      ' using the custom format string and display.
      Dim utcstr As [String] = utcdt.ToString(format)
      Console.WriteLine(utcstr)

      ' Converts the string back to a local DateTime and displays it.
      Dim parsedBack As DateTime = DateTime.ParseExact(str, format, 
            en.DateTimeFormat)
      Console.WriteLine(parsedBack)

      ' Converts the string back to a UTC DateTime and displays it.
      ' If you do not use the DateTime.ParseExact method that takes
      ' a DateTimeStyles.AdjustToUniversal value, the parsed DateTime
      ' will not include the time zone information. 
      Dim parsedBackUTC As DateTime = DateTime.ParseExact(str, format, _
            en.DateTimeFormat, DateTimeStyles.AdjustToUniversal)
      Console.WriteLine(parsedBackUTC)
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class TimeZoneSample
{
   public static void Main()
   {
      CultureInfo en = new CultureInfo("en-US");
      Thread.CurrentThread.CurrentCulture = en;

      // Creates a DateTime for the local time.
      DateTime dt = new DateTime(2001, 7, 13, 4, 0, 0);

      // Converts the local DateTime to the UTC time.
      DateTime utcdt = dt.ToUniversalTime();

      // Defines a custom string format to display the DateTime value.
      // zzzz specifies the full time zone offset.
      String format = "MM/dd/yyyy hh:mm:sszzz";

      // Converts the local DateTime to a string 
      // using the custom format string and display.
      String str = dt.ToString(format);
      Console.WriteLine(str);

      // Converts the UTC DateTime to a string 
      // using the custom format string and display.
      String utcstr = utcdt.ToString(format);
      Console.WriteLine(utcstr);

      // Converts the string back to a local DateTime and displays it.
      DateTime parsedBack =
            DateTime.ParseExact(str,format,en.DateTimeFormat);
      Console.WriteLine(parsedBack);

      // Converts the string back to a UTC DateTime and displays it.
      // If you do not use the DateTime.ParseExact method that takes
      // a DateTimeStyles.AdjustToUniversal value, the parsed DateTime
      // object will not include the time zone information.
      DateTime parsedBackUTC = DateTime.ParseExact(str,format, _
            en.DateTimeFormat, DateTimeStyles.AdjustToUniversal);
      Console.WriteLine(parsedBackUTC);
   }
}

這個程式碼產生下列輸出:

07/13/2001 04:00:00-07:00
07/13/2001 11:00:00-07:00
7/13/2001 4:00:00 AM
7/13/2001 11:00:00 AM

使用 DateTime 成員

當您使用 DateTime 結構時,請注意如 Day 等成員是以西曆做為基礎。即使您的應用程式變更目前的日曆,或允許使用者透過 [控制台] 中的地區及語言選項變更日期和時間設定,系統仍將使用西曆來執行 DateTime 方法的計算,這可避免這些方法所執行的算術被使用者的設定所破壞。如果您要應用程式根據目前的日曆來執行區分文化特性的日期和時間作業,您必須使用 Calendar 屬性來呼叫 Calendar 類別提供的方法,例如 GetDayOfMonth。如需 DateTime 成員和 Calendar 成員所擷取值差別的範例,請參閱使用特定文化特性的日曆

使用 DateTime 結構時,請注意 DateTime 型別是不變的值。因此,如 AddDays 等方法會擷取新的 DateTime 值,而非累加現有的值。下列範例將示範如何使用陳述式 dt = dt.AddDays(1) 將 DateTime 型別累加一天。

Imports System
Imports System.Globalization
Imports System.Threading
Imports Microsoft.VisualBasic

Public Class TestClass
   
   Public Shared Sub Main()
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      
      Dim dt As DateTime = DateTime.Now
      Console.WriteLine(ControlChars.Newline + " Today is {0}", _
         DateTime.Now.ToString("d"))
      
      ' Increments dt by one day.
      dt = dt.AddDays(1)
      Console.WriteLine(ControlChars.Newline + " Tomorrow is {0}", _
         dt.ToString("d"))
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class TestClass
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

      DateTime dt = DateTime.Now;
      Console.WriteLine("Today is {0}", DateTime.Now.ToString("d"));

      // Increments dt by one day.
      dt = dt.AddDays(1);
      Console.WriteLine("Tomorrow is {0}", dt.ToString("d"));

   }
}

如果您在 2001 年 8 月 3 日執行這個程式碼,它將顯示下列輸出:

Today is 8/3/2001
Tomorrow is 8/4/2001

請參閱

概念

日期和時間格式字串

其他資源

編碼和當地語系化