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

DateTime 結構提供例如 DateTime.ToStringDateTime.Parse 的方法,以便您在 DateTime 上執行區分文化特性的作業。您可以使用 DateTimeFormatInfo 類別根據文化特性來格式化和顯示 DateTimeDateTimeFormatInfo 定義格式化和顯示 DateTime 值的方式,是文化特性而定。例如,如果您使用 ShortDatePattern,日期 2001 年 2 月 1 日將格式化為 "en-US" 的 2/1/2001 和 "en-GB" 文化特性的 01/02/2001。

您可以為特定文化特性 (或不變文化特性) 建立 DateTimeFormatInfo 的執行個體,但請不要為中性文化特性建立執行個體。中性文化特性並未提供足夠的資訊來顯示正確的日期格式。如果您嘗試使用中性文化特性建立 DateTimeFormatInfo 的執行個體,將擲回一則例外狀況。如需其他資訊和使用 DateTime 格式的範例,請參閱日期和時間格式字串

下列程式碼範例在 CurrentThread.CurrentCulture 設為 "en-US" (美國英文),然後設為 "de-DE" (德國德文) 時,使用 DateTimeFormatInfo.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 結構中的方法和屬性一律使用當地的時區來進行計算和比對。使用 DateTime.Parse 方法和 DateTime.ParseExact 方法時,請特別注意這點。這些方法提供多載,可將日期和時間的字串表示轉換成 DateTime 型別。您也可以選擇格式化特定文化特性的 DateTime。如果您並未再傳送給這些方法的字串中指定時區,它們將不執行時區調整,然後傳回剖析的日期和時間。該日期和時間將依據系統的時區設定而來。如果您指定時區位移 (Offset),這些方法將會剖析日期/時間字串,接著將它轉換成 Coordinated Universal Time (UTC;先前稱為 Greenwich Mean Time (GMT)),最後再將它轉換成當地系統時間。

您可以使用 DateTime.ToUniversalTime 方法來轉換當地系統 DateTime 到其對等的 UTC。若要剖析日期/時間字串並將之轉換為 UTC DateTime,您可以搭配使用 DateTimeStyles 列舉型別 AdjustToUniversal 值與 DateTime.ParseDateTime.ParseExact 方法。這些 DateTime 處理方式將在下列程式碼範例中展示。這個範例建立為當地時間建立 DateTime,然後將它轉換成 UTC 對等 DateTime。這兩種型別都會轉換成字串並寫入主控台中。請注意,該字串會音當地時間和 Coordinated Universal Time (UTC) 之間的位移而有所不同。如需不同時區的 UTC 位移的詳細資訊,請參閱 TimeZone.GetUtcOffset 方法。這些字串將使用 DateTime.ParseExact 方法轉換回 DateTime 型別。請注意,為取得儲存在 utcdt 中的時區資訊,AdjustToUniversal 值必須指定為 DateTime.ParseExact 方法的參數。

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 結構提供的方法時,您必須注意例如以下所列成員是以西曆作基礎的,這些成員包括 DateTime.DayDateTime.MonthDateTime.YearDateTime.AddDays。即使您變更您應用程式碼中的目前日曆,或透過 [控制台] 的 [地區及語言選項] 對話方塊變更日期和時間設定,系統仍將使用西曆來執行這些方法的計算。這個功能可避免這些方法所執行的算術被使用者的設定配破壞。如果您要根據目前的日曆來執行區分文化特性的日期和時間作業,您必須使用 DateTimeFormatInfo.Calendar 屬性來呼叫 Calendar 類別提供的方法,例如 Calendar.GetDayOfMonthCalendar.GetMonthCalendar.GetYearCalendar.AddDays。如需 DateTime 成員和 Calendar 類別成員傳回的不同數值範例,請參閱使用特定文化特性的日曆

使用 DateTime 結構時,請注意 DateTime 是實值型別 (Value Type),而且是不變的。因此,類似 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

請參閱

參考

DateTime

概念

日期和時間格式字串

其他資源

編碼和當地語系化