Formattazione di data e ora per una lingua specifica

La struttura DateTime fornisce metodi, quali DateTime.ToString e DateTime.Parse, che consentono di eseguire operazioni dipendenti dalla lingua su DateTime. Utilizzare la classe DateTimeFormatInfo per formattare e visualizzare un DateTime in base alla lingua. DateTimeFormatInfo definisce la modalità di formattazione e visualizzazione dei valori DateTime in base alla lingua. Tramite ShortDatePattern, ad esempio, la data 1 febbraio 2001 viene formattata come 2/1/2001 per la lingua "en-US" (inglese statunitense) e 01/02/2001 per la lingua "en-GB" (inglese britannico).

È possibile creare un'istanza di DateTimeFormatInfo per una lingua specifica o per la lingua inglese, ma non per una lingua non associata ad alcun paese. Una lingua non associata ad alcun paese non fornisce informazioni sufficienti per visualizzare il formato di data corretto. Se si cerca di creare un'istanza di DateTimeFormatInfo utilizzando una lingua non associata ad alcun paese, viene generata un'eccezione. Per ulteriori informazioni ed esempi sull'uso della formattazione DateTime, vedere Stringhe di formato di data e ora.

Nell'esempio di codice seguente viene visualizzata la data corrente tramite DateTimeFormatInfo.ShortDatePattern quando CurrentThread.CurrentCulture viene impostato su "en-US", l'inglese parlato negli Stati Uniti, quindi su "de-DE", il tedesco parlato in Germania.

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));
   }
}

Se si esegue questo codice in data 9 luglio 2001, l'output avrà il seguente aspetto:

7/9/2001
09.07.2001

Operazioni con i fusi orari

I metodi e le proprietà nella struttura DateTime utilizzano sempre il fuso orario locale per i calcoli e i confronti. È opportuno tenere presente questo aspetto quando si utilizzano i metodi DateTime.Parse e DateTime.ParseExact. Questi metodi forniscono gli overload che consentono di convertire la rappresentazione in forma di stringa di una data e un'ora su un tipo DateTime. È possibile anche scegliere di formattare un valore DateTime per una lingua specifica. Se non si specifica un fuso orario nella stringa passata a questi metodi, vengono restituite la data e l'ora analizzate senza eseguire un adattamento del fuso orario. La data e l'ora sono basate sull'impostazione del fuso orario del sistema. Se si specifica uno scarto di fuso orario, questi metodi analizzano la stringa di data e ora e ne eseguono la conversione in formato UTC (Coordinated Universal Time), noto in precedenza come GMT (Greenwich Mean Time), e quindi nell'ora nel sistema locale.

Utilizzare il metodo DateTime.ToUniversalTime per convertire un DateTime locale nel valore UTC corrispondente. Per analizzare una stringa di data e ora ed eseguirne la conversione in un DateTime UTC, utilizzare il valore AdjustToUniversal dell'enumerazione DateTimeStyles con il metodo DateTime.Parse o DateTime.ParseExact. Queste manipolazioni di DateTime vengono illustrate nell'esempio di codice seguente. In questo esempio viene creato un DateTime per l'ora locale, quindi viene eseguita la conversione nel valore DateTime UTC equivalente. Entrambi i tipi vengono convertiti in stringhe e scritti nella console. Si noti che le stringhe differiscono dallo scarto UTC tra il fuso orario locale e l'ora UTC (Tempo universale coordinato, Coordinated Universal Time). Per ulteriori informazioni sullo scarto UTC per i diversi fusi orari, vedere Metodo TimeZone.GetUtcOffset. Queste stringhe vengono convertite di nuovo nei tipi DateTime tramite il metodo DateTime.ParseExact. Si noti che, per catturare le informazioni sul fuso orario archiviate in utcdt, è necessario specificare il valore AdjustToUniversal come parametro per il metodo 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);
   }
}

L'output del codice è il seguente:

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

Operazioni con i membri DateTime

Quando si utilizzano i metodi forniti dalla struttura DateTime, è necessario tenere presente che i membri come DateTime.Day, DateTime.Month, DateTime.Year e DateTime.AddDays sono basati sul calendario gregoriano. Anche se si cambia il calendario corrente nel codice dell'applicazione o si cambiano le impostazioni di data e ora tramite la finestra di dialogo Impostazioni internazionali nel Pannello di controllo, il calendario gregoriano continua a essere utilizzato per eseguire i calcoli per questi metodi. Questa funzionalità impedisce che i calcoli eseguiti da questi metodi vengano alterati dalle impostazioni di un utente. Se si desidera eseguire operazioni su data e ora dipendenti dalla lingua in base al calendario corrente, è necessario utilizzare la proprietà DateTimeFormatInfo.Calendar per chiamare metodi forniti dalla classe Calendar, quali Calendar.GetDayOfMonth, Calendar.GetMonth, Calendar.GetYear e Calendar.AddDays. Per un esempio sui diversi valori restituiti dai membri DateTime e dai membri di classe Calendar, vedere Uso di calendari per lingue specifiche.

Quando si utilizza la struttura DateTime, tenere presente che DateTime è un tipo che rappresenta un valore ed è immutabile. Operazioni, come ad esempio DateTime.AddDays, restituiscono un nuovo valore DateTime anziché incrementare un valore esistente. Nell'esempio seguente viene illustrato come incrementare un DateTime di un giorno utilizzando l'istruzione dt = dt.AddDays(1).

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"));

   }
}

Se si esegue questo codice in data 3 agosto 2001, l'output avrà il seguente aspetto:

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

Vedere anche

Riferimenti

DateTime

Concetti

Stringhe di formato di data e ora

Altre risorse

Codifica e localizzazione