DateTime.ToString Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente.
Overload
ToString(String, IFormatProvider) |
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando il formato specificato e le informazioni sul formato specifiche delle impostazioni cultura indicate. |
ToString(String) |
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando il formato specificato e le convenzioni di formattazione delle impostazioni cultura. |
ToString(IFormatProvider) |
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando le informazioni sul formato relative alle impostazioni cultura specificate. |
ToString() |
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando le convenzioni di formattazione delle impostazioni cultura. |
ToString(String, IFormatProvider)
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando il formato specificato e le informazioni sul formato specifiche delle impostazioni cultura indicate.
public:
virtual System::String ^ ToString(System::String ^ format, IFormatProvider ^ provider);
public string ToString (string format, IFormatProvider provider);
public string ToString (string? format, IFormatProvider? provider);
override this.ToString : string * IFormatProvider -> string
Public Function ToString (format As String, provider As IFormatProvider) As String
Parametri
- format
- String
Stringa di formato di data e ora standard o personalizzato.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.
Restituisce
Rappresentazione di stringa del valore dell'oggetto DateTime corrente, specificata dai parametri format
e provider
.
Implementazioni
Eccezioni
La lunghezza di format
è 1 e non è uno dei caratteri identificatori di formato definiti per DateTimeFormatInfo.
-oppure-
format
non contiene un modello di formato personalizzato valido.
La data e l'ora non sono comprese nell'intervallo di date supportato dal calendario usato da provider
.
Esempio
Nell'esempio seguente viene utilizzata ognuna delle stringhe di formato di data e ora standard per visualizzare la rappresentazione di stringa di una data e di un'ora per quattro impostazioni cultura diverse.
using System;
using System.Globalization;
public class Example
{
public static void Main1()
{
// Create an array of all supported standard date and time format specifiers.
string[] formats = {"d", "D", "f", "F", "g", "G", "m", "o", "r",
"s", "t", "T", "u", "U", "Y"};
// Create an array of four cultures.
CultureInfo[] cultures = {CultureInfo.GetCultureInfo("de-DE"),
CultureInfo.GetCultureInfo("en-US"),
CultureInfo.GetCultureInfo("es-ES"),
CultureInfo.GetCultureInfo("fr-FR")};
// Define date to be displayed.
DateTime dateToDisplay = new DateTime(2008, 10, 31, 17, 4, 32);
// Iterate each standard format specifier.
foreach (string formatSpecifier in formats)
{
foreach (CultureInfo culture in cultures)
Console.WriteLine("{0} Format Specifier {1, 10} Culture {2, 40}",
formatSpecifier, culture.Name,
dateToDisplay.ToString(formatSpecifier, culture));
Console.WriteLine();
}
}
}
// The example displays the following output:
// d Format Specifier de-DE Culture 31.10.2008
// d Format Specifier en-US Culture 10/31/2008
// d Format Specifier es-ES Culture 31/10/2008
// d Format Specifier fr-FR Culture 31/10/2008
//
// D Format Specifier de-DE Culture Freitag, 31. Oktober 2008
// D Format Specifier en-US Culture Friday, October 31, 2008
// D Format Specifier es-ES Culture viernes, 31 de octubre de 2008
// D Format Specifier fr-FR Culture vendredi 31 octobre 2008
//
// f Format Specifier de-DE Culture Freitag, 31. Oktober 2008 17:04
// f Format Specifier en-US Culture Friday, October 31, 2008 5:04 PM
// f Format Specifier es-ES Culture viernes, 31 de octubre de 2008 17:04
// f Format Specifier fr-FR Culture vendredi 31 octobre 2008 17:04
//
// F Format Specifier de-DE Culture Freitag, 31. Oktober 2008 17:04:32
// F Format Specifier en-US Culture Friday, October 31, 2008 5:04:32 PM
// F Format Specifier es-ES Culture viernes, 31 de octubre de 2008 17:04:32
// F Format Specifier fr-FR Culture vendredi 31 octobre 2008 17:04:32
//
// g Format Specifier de-DE Culture 31.10.2008 17:04
// g Format Specifier en-US Culture 10/31/2008 5:04 PM
// g Format Specifier es-ES Culture 31/10/2008 17:04
// g Format Specifier fr-FR Culture 31/10/2008 17:04
//
// G Format Specifier de-DE Culture 31.10.2008 17:04:32
// G Format Specifier en-US Culture 10/31/2008 5:04:32 PM
// G Format Specifier es-ES Culture 31/10/2008 17:04:32
// G Format Specifier fr-FR Culture 31/10/2008 17:04:32
//
// m Format Specifier de-DE Culture 31. Oktober
// m Format Specifier en-US Culture October 31
// m Format Specifier es-ES Culture 31 de octubre
// m Format Specifier fr-FR Culture 31 octobre
//
// o Format Specifier de-DE Culture 2008-10-31T17:04:32.0000000
// o Format Specifier en-US Culture 2008-10-31T17:04:32.0000000
// o Format Specifier es-ES Culture 2008-10-31T17:04:32.0000000
// o Format Specifier fr-FR Culture 2008-10-31T17:04:32.0000000
//
// r Format Specifier de-DE Culture Fri, 31 Oct 2008 17:04:32 GMT
// r Format Specifier en-US Culture Fri, 31 Oct 2008 17:04:32 GMT
// r Format Specifier es-ES Culture Fri, 31 Oct 2008 17:04:32 GMT
// r Format Specifier fr-FR Culture Fri, 31 Oct 2008 17:04:32 GMT
//
// s Format Specifier de-DE Culture 2008-10-31T17:04:32
// s Format Specifier en-US Culture 2008-10-31T17:04:32
// s Format Specifier es-ES Culture 2008-10-31T17:04:32
// s Format Specifier fr-FR Culture 2008-10-31T17:04:32
//
// t Format Specifier de-DE Culture 17:04
// t Format Specifier en-US Culture 5:04 PM
// t Format Specifier es-ES Culture 17:04
// t Format Specifier fr-FR Culture 17:04
//
// T Format Specifier de-DE Culture 17:04:32
// T Format Specifier en-US Culture 5:04:32 PM
// T Format Specifier es-ES Culture 17:04:32
// T Format Specifier fr-FR Culture 17:04:32
//
// u Format Specifier de-DE Culture 2008-10-31 17:04:32Z
// u Format Specifier en-US Culture 2008-10-31 17:04:32Z
// u Format Specifier es-ES Culture 2008-10-31 17:04:32Z
// u Format Specifier fr-FR Culture 2008-10-31 17:04:32Z
//
// U Format Specifier de-DE Culture Freitag, 31. Oktober 2008 09:04:32
// U Format Specifier en-US Culture Friday, October 31, 2008 9:04:32 AM
// U Format Specifier es-ES Culture viernes, 31 de octubre de 2008 9:04:32
// U Format Specifier fr-FR Culture vendredi 31 octobre 2008 09:04:32
//
// Y Format Specifier de-DE Culture Oktober 2008
// Y Format Specifier en-US Culture October 2008
// Y Format Specifier es-ES Culture octubre de 2008
// Y Format Specifier fr-FR Culture octobre 2008
Imports System.Globalization
Module Example
Public Sub Main4()
' Create an array of all supported standard date and time format specifiers.
Dim formats() As String = {"d", "D", "f", "F", "g", "G", "m", "o", "r",
"s", "t", "T", "u", "U", "Y"}
' Create an array of four cultures.
Dim cultures() As CultureInfo = {CultureInfo.GetCultureInfo("de-DE"),
CultureInfo.GetCultureInfo("en-US"),
CultureInfo.GetCultureInfo("es-ES"),
CultureInfo.GetCultureInfo("fr-FR")}
' Define date to be displayed.
Dim dateToDisplay As Date = #10/1/2008 17:04:32#
' Iterate each standard format specifier.
For Each formatSpecifier As String In formats
For Each culture As CultureInfo In cultures
Console.WriteLine("{0} Format Specifier {1, 10} Culture {2, 40}",
formatSpecifier, culture.Name,
dateToDisplay.ToString(formatSpecifier, culture))
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' d Format Specifier de-DE Culture 01.10.2008
' d Format Specifier en-US Culture 10/1/2008
' d Format Specifier es-ES Culture 01/10/2008
' d Format Specifier fr-FR Culture 01/10/2008
'
' D Format Specifier de-DE Culture Mittwoch, 1. Oktober 2008
' D Format Specifier en-US Culture Wednesday, October 01, 2008
' D Format Specifier es-ES Culture miércoles, 01 de octubre de 2008
' D Format Specifier fr-FR Culture mercredi 1 octobre 2008
'
' f Format Specifier de-DE Culture Mittwoch, 1. Oktober 2008 17:04
' f Format Specifier en-US Culture Wednesday, October 01, 2008 5:04 PM
' f Format Specifier es-ES Culture miércoles, 01 de octubre de 2008 17:04
' f Format Specifier fr-FR Culture mercredi 1 octobre 2008 17:04
'
' F Format Specifier de-DE Culture Mittwoch, 1. Oktober 2008 17:04:32
' F Format Specifier en-US Culture Wednesday, October 01, 2008 5:04:32 PM
' F Format Specifier es-ES Culture miércoles, 01 de octubre de 2008 17:04:3
' F Format Specifier fr-FR Culture mercredi 1 octobre 2008 17:04:32
'
' g Format Specifier de-DE Culture 01.10.2008 17:04
' g Format Specifier en-US Culture 10/1/2008 5:04 PM
' g Format Specifier es-ES Culture 01/10/2008 17:04
' g Format Specifier fr-FR Culture 01/10/2008 17:04
'
' G Format Specifier de-DE Culture 01.10.2008 17:04:32
' G Format Specifier en-US Culture 10/1/2008 5:04:32 PM
' G Format Specifier es-ES Culture 01/10/2008 17:04:32
' G Format Specifier fr-FR Culture 01/10/2008 17:04:32
'
' m Format Specifier de-DE Culture 01 Oktober
' m Format Specifier en-US Culture October 01
' m Format Specifier es-ES Culture 01 octubre
' m Format Specifier fr-FR Culture 1 octobre
'
' o Format Specifier de-DE Culture 2008-10-01T17:04:32.0000000
' o Format Specifier en-US Culture 2008-10-01T17:04:32.0000000
' o Format Specifier es-ES Culture 2008-10-01T17:04:32.0000000
' o Format Specifier fr-FR Culture 2008-10-01T17:04:32.0000000
'
' r Format Specifier de-DE Culture Wed, 01 Oct 2008 17:04:32 GMT
' r Format Specifier en-US Culture Wed, 01 Oct 2008 17:04:32 GMT
' r Format Specifier es-ES Culture Wed, 01 Oct 2008 17:04:32 GMT
' r Format Specifier fr-FR Culture Wed, 01 Oct 2008 17:04:32 GMT
'
' s Format Specifier de-DE Culture 2008-10-01T17:04:32
' s Format Specifier en-US Culture 2008-10-01T17:04:32
' s Format Specifier es-ES Culture 2008-10-01T17:04:32
' s Format Specifier fr-FR Culture 2008-10-01T17:04:32
'
' t Format Specifier de-DE Culture 17:04
' t Format Specifier en-US Culture 5:04 PM
' t Format Specifier es-ES Culture 17:04
' t Format Specifier fr-FR Culture 17:04
'
' T Format Specifier de-DE Culture 17:04:32
' T Format Specifier en-US Culture 5:04:32 PM
' T Format Specifier es-ES Culture 17:04:32
' T Format Specifier fr-FR Culture 17:04:32
'
' u Format Specifier de-DE Culture 2008-10-01 17:04:32Z
' u Format Specifier en-US Culture 2008-10-01 17:04:32Z
' u Format Specifier es-ES Culture 2008-10-01 17:04:32Z
' u Format Specifier fr-FR Culture 2008-10-01 17:04:32Z
'
' U Format Specifier de-DE Culture Donnerstag, 2. Oktober 2008 00:04:32
' U Format Specifier en-US Culture Thursday, October 02, 2008 12:04:32 AM
' U Format Specifier es-ES Culture jueves, 02 de octubre de 2008 0:04:32
' U Format Specifier fr-FR Culture jeudi 2 octobre 2008 00:04:32
'
' Y Format Specifier de-DE Culture Oktober 2008
' Y Format Specifier en-US Culture October, 2008
' Y Format Specifier es-ES Culture octubre de 2008
' Y Format Specifier fr-FR Culture octobre 2008
Nell'esempio seguente vengono illustrati diversi modi per formattare DateTime un valore usando l'oggetto invariante. DateTimeFormatInfo
using namespace System;
using namespace System::Globalization;
void main()
{
DateTime dt = DateTime::Now;
array<String^>^format = {L"d",L"D",L"f",L"F",L"g",L"G",L"m",L"r",L"s",L"t",L"T",L"u",L"U",L"y",L"dddd, MMMM dd yyyy",L"ddd, MMM d \"'\"yy",L"dddd, MMMM dd",L"M/yy",L"dd-MM-yy"};
String^ date;
for ( int i = 0; i < format->Length; i++ )
{
date = dt.ToString( format[ i ], DateTimeFormatInfo::InvariantInfo );
Console::WriteLine( String::Concat( format[ i ], L" :", date ) );
}
/** Output.
*
* d :08/17/2000
* D :Thursday, August 17, 2000
* f :Thursday, August 17, 2000 16:32
* F :Thursday, August 17, 2000 16:32:32
* g :08/17/2000 16:32
* G :08/17/2000 16:32:32
* m :August 17
* r :Thu, 17 Aug 2000 23:32:32 GMT
* s :2000-08-17T16:32:32
* t :16:32
* T :16:32:32
* u :2000-08-17 23:32:32Z
* U :Thursday, August 17, 2000 23:32:32
* y :August, 2000
* dddd, MMMM dd yyyy :Thursday, August 17 2000
* ddd, MMM d "'"yy :Thu, Aug 17 '00
* dddd, MMMM dd :Thursday, August 17
* M/yy :8/00
* dd-MM-yy :17-08-00
*/
}
using System;
using System.Globalization;
public class MainClass
{
public static void Main(string[] args)
{
DateTime dt = DateTime.Now;
String[] format = {
"d", "D",
"f", "F",
"g", "G",
"m",
"r",
"s",
"t", "T",
"u", "U",
"y",
"dddd, MMMM dd yyyy",
"ddd, MMM d \"'\"yy",
"dddd, MMMM dd",
"M/yy",
"dd-MM-yy",
};
string date;
for (int i = 0; i < format.Length; i++)
{
date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);
Console.WriteLine(string.Concat(format[i], " :", date));
}
/** Output.
*
* d :08/17/2000
* D :Thursday, August 17, 2000
* f :Thursday, August 17, 2000 16:32
* F :Thursday, August 17, 2000 16:32:32
* g :08/17/2000 16:32
* G :08/17/2000 16:32:32
* m :August 17
* r :Thu, 17 Aug 2000 23:32:32 GMT
* s :2000-08-17T16:32:32
* t :16:32
* T :16:32:32
* u :2000-08-17 23:32:32Z
* U :Thursday, August 17, 2000 23:32:32
* y :August, 2000
* dddd, MMMM dd yyyy :Thursday, August 17 2000
* ddd, MMM d "'"yy :Thu, Aug 17 '00
* dddd, MMMM dd :Thursday, August 17
* M/yy :8/00
* dd-MM-yy :17-08-00
*/
}
}
Option Explicit
Option Strict
Imports System.Globalization
Public Class MainClass
Public Shared Sub Main()
Dim dt As DateTime = DateTime.Now
Dim myformat() As String = {"d", "D", _
"f", "F", _
"g", "G", _
"m", _
"r", _
"s", _
"t", "T", _
"u", "U", _
"y", _
"dddd, MMMM dd yyyy", _
"ddd, MMM d ""'""yy", _
"dddd, MMMM dd", _
"M/yy", _
"dd-MM-yy"}
Dim mydate As String
Dim i As Integer
For i = 0 To myformat.Length - 1
mydate = dt.ToString(myformat(i), DateTimeFormatInfo.InvariantInfo)
Console.WriteLine(String.Concat(myformat(i), " :", mydate))
Next i
' Output.
'
' d :08/17/2000
' D :Thursday, August 17, 2000
' f :Thursday, August 17, 2000 16:32
' F :Thursday, August 17, 2000 16:32:32
' g :08/17/2000 16:32
' G :08/17/2000 16:32:32
' m :August 17
' r :Thu, 17 Aug 2000 23:32:32 GMT
' s :2000-08-17T16:32:32
' t :16:32
' T :16:32:32
' u :2000-08-17 23:32:32Z
' U :Thursday, August 17, 2000 23:32:32
' y :August, 2000
' dddd, MMMM dd yyyy :Thursday, August 17 2000
' ddd, MMM d "'"yy :Thu, Aug 17 '00
' dddd, MMMM dd :Thursday, August 17
' M/yy :8/00
' dd-MM-yy :17-08-00
End Sub
End Class
Commenti
Il parametro può contenere un singolo carattere identificatore di formato (vedere Stringhe di formato di data e ora standard) o un modello di formato personalizzato (vedere Stringhe di formato di data format
e ora personalizzate). Se format
è o una stringa vuota null
(""), viene usato l'identificatore di formato standard, "G".
Il parametro definisce il modello che corrisponde agli identificatori di formato standard, nonché i simboli e i nomi provider
dei componenti di data e ora. Il provider
parametro può essere uno dei seguenti:
Oggetto che rappresenta le impostazioni cultura le cui convenzioni di formattazione CultureInfo devono essere riflesse nella stringa restituita. DateTimeFormatInfoL'oggetto restituito CultureInfo.DateTimeFormat dalla proprietà definisce la formattazione della stringa restituita.
Oggetto DateTimeFormatInfo che definisce il formato dei dati di data e ora.
Oggetto personalizzato che implementa IFormatProvider l'interfaccia . Il GetFormat metodo restituisce un oggetto che fornisce informazioni di DateTimeFormatInfo formattazione.
Se provider
è , viene utilizzato null
DateTimeFormatInfo l'oggetto associato alle impostazioni cultura correnti. Per altre informazioni, vedere CultureInfo.CurrentCulture.
Note per i chiamanti
Il ToString(String, IFormatProvider) metodo restituisce la rappresentazione di stringa della data e dell'ora nel calendario utilizzato dal parametro provider
. Il calendario è definito dalla Calendar proprietà . Se il valore dell'istanza DateTime corrente è precedente o successivo a , il metodo genera MinSupportedDateTime MaxSupportedDateTime un'eccezione ArgumentOutOfRangeException . Nell'esempio seguente viene illustrato questo concetto. Tenta di formattare una data che non rientra nell'intervallo della UmAlQuraCalendar classe .
Vedi anche
- DateTimeFormatInfo
- CultureInfo
- Formattazione di tipi in .NET
- Stringhe di formato di data e ora standard
- Stringhe di formato di data e ora personalizzato
- Esempio: Utilità di formattazione di .NET Core WinForms (C#)
- Esempio: Utilità di formattazione di .NET Core WinForms (Visual Basic)
Si applica a
ToString(String)
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando il formato specificato e le convenzioni di formattazione delle impostazioni cultura.
public:
System::String ^ ToString(System::String ^ format);
public string ToString (string format);
public string ToString (string? format);
override this.ToString : string -> string
Public Function ToString (format As String) As String
Parametri
- format
- String
Stringa di formato di data e ora standard o personalizzato.
Restituisce
Rappresentazione di stringa del valore dell'oggetto DateTime corrente, come specificato da format
.
Eccezioni
La lunghezza di format
è 1 e non è uno dei caratteri identificatori di formato definiti per DateTimeFormatInfo.
-oppure-
format
non contiene un modello di formato personalizzato valido.
La data e l'ora non sono comprese nell'intervallo di date supportato dal calendario usato dalle impostazioni cultura correnti.
Esempio
Nell'esempio seguente vengono utilizzate ognuna delle stringhe di formato di data e ora standard e una selezione di stringhe di formato di data e ora personalizzate per visualizzare la rappresentazione di stringa di un DateTime valore. Le impostazioni cultura correnti del thread per l'esempio sono en-US.
using System;
public class DateToStringExample2
{
public static void Main0()
{
DateTime dateValue = new DateTime(2008, 6, 15, 21, 15, 07);
// 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.
foreach (string standardFmt in standardFmts)
Console.WriteLine("{0}: {1}", standardFmt,
dateValue.ToString(standardFmt));
Console.WriteLine();
// 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)
Console.WriteLine("'{0}': {1}", customFmt,
dateValue.ToString(customFmt));
}
}
// This example displays the following output to the console:
// d: 6/15/2008
// D: Sunday, June 15, 2008
// f: Sunday, June 15, 2008 9:15 PM
// F: Sunday, June 15, 2008 9:15:07 PM
// g: 6/15/2008 9:15 PM
// G: 6/15/2008 9:15:07 PM
// m: June 15
// o: 2008-06-15T21:15:07.0000000
// R: Sun, 15 Jun 2008 21:15:07 GMT
// s: 2008-06-15T21:15:07
// t: 9:15 PM
// T: 9:15:07 PM
// u: 2008-06-15 21:15:07Z
// U: Monday, June 16, 2008 4:15:07 AM
// y: June, 2008
//
// 'h:mm:ss.ff t': 9:15:07.00 P
// 'd MMM yyyy': 15 Jun 2008
// 'HH:mm:ss.f': 21:15:07.0
// 'dd MMM HH:mm:ss': 15 Jun 21:15:07
// '\Mon\t\h\: M': Month: 6
// 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00
Module DateToStringExample2
Public Sub Main2()
Dim dateValue As Date = #6/15/2008 9:15:07PM#
' Create an array of standard format strings.
Dim standardFmts() As String = {"d", "D", "f", "F", "g", "G",
"m", "o", "R", "s", "t", "T",
"u", "U", "y"}
' Output date and time using each standard format string.
For Each standardFmt As String In standardFmts
Console.WriteLine("{0}: {1}", standardFmt,
dateValue.ToString(standardFmt))
Next
Console.WriteLine()
' Create an array of some custom format strings.
Dim customFmts() As String = {"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.
For Each customFmt As String In customFmts
Console.WriteLine("'{0}': {1}", customFmt,
dateValue.ToString(customFmt))
Next
End Sub
End Module
' This example displays the following output to the console:
' d: 6/15/2008
' D: Sunday, June 15, 2008
' f: Sunday, June 15, 2008 9:15 PM
' F: Sunday, June 15, 2008 9:15:07 PM
' g: 6/15/2008 9:15 PM
' G: 6/15/2008 9:15:07 PM
' m: June 15
' o: 2008-06-15T21:15:07.0000000
' R: Sun, 15 Jun 2008 21:15:07 GMT
' s: 2008-06-15T21:15:07
' t: 9:15 PM
' T: 9:15:07 PM
' u: 2008-06-15 21:15:07Z
' U: Monday, June 16, 2008 4:15:07 AM
' y: June, 2008
'
' 'h:mm:ss.ff t': 9:15:07.00 P
' 'd MMM yyyy': 15 Jun 2008
' 'HH:mm:ss.f': 21:15:07.0
' 'dd MMM HH:mm:ss': 15 Jun 21:15:07
' '\Mon\t\h\: M': Month: 6
' 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00
Commenti
Il metodo restituisce la rappresentazione di stringa di un valore di data e ora in un formato specifico che usa le convenzioni di formattazione delle impostazioni cultura correnti. Per altre ToString(String) informazioni, vedere CultureInfo.CurrentCulture .
Il parametro deve contenere un singolo carattere identificatore di formato (vedere Stringhe di formato di data e ora standard) o un modello di formato personalizzato (vedere Stringhe di formato di data e ora personalizzato) che definisce il formato della stringa format
restituita. Se format
è o una stringa null
vuota, viene usato l'identificatore di formato generale "G".
Alcuni usi di questo metodo includono:
Recupero di una stringa che visualizza la data e l'ora nel formato di data e ora breve delle impostazioni cultura correnti. A tale scopo, usare l'identificatore di formato "G".
Recupero di una stringa contenente solo il mese e l'anno. A tale scopo, usare la stringa di formato "MM/aaaa". La stringa di formato usa il separatore di data delle impostazioni cultura correnti.
Recupero di una stringa contenente la data e l'ora in un formato specifico. Ad esempio, la stringa di formato "MM/gg/aHH:mm" visualizza la stringa di data e ora in un formato fisso, ad esempio "19//03//2013 18:06". La stringa di formato usa "/" come separatore di data fisso indipendentemente dalle impostazioni cultura specifiche.
Recupero di una data in un formato ridotto che può essere usato per serializzare una stringa di data. Ad esempio, la stringa di formato "yyyyMMdd" visualizza un anno a quattro cifre seguito da un mese a due cifre e da un giorno a due cifre senza separatore di data.
Nell'esempio seguente vengono utilizzate queste tre stringhe di formato per visualizzare un valore di data e ora usando le convenzioni delle impostazioni cultura en-US e fr-FR.
using System;
using System.Globalization;
public class Example3
{
public static void Main3()
{
string[] formats = { "G", "MM/yyyy", @"MM\/dd\/yyyy HH:mm", "yyyyMMdd" };
string[] cultureNames = { "en-US", "fr-FR" };
DateTime date = new DateTime(2015, 8, 18, 13, 31, 17);
foreach (var cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
CultureInfo.CurrentCulture = culture;
Console.WriteLine(culture.NativeName);
foreach (var format in formats)
Console.WriteLine($" {format}: {date.ToString(format)}");
Console.WriteLine();
}
}
}
// The example displays the following output:
// English (United States)
// G: 8/18/2015 1:31:17 PM
// MM/yyyy: 08/2015
// MM\/dd\/yyyy HH:mm: 08/18/2015 13:31
// yyyyMMdd: 20150818
//
// français (France)
// G: 18/08/2015 13:31:17
// MM/yyyy: 08/2015
// MM\/dd\/yyyy HH:mm: 08/18/2015 13:31
// yyyyMMdd: 20150818
Imports System.Globalization
Imports System.Threading
Public Module Example5
Public Sub Main5()
Dim formats() As String = {"G", "MM/yyyy", "MM\/dd\/yyyy HH:mm",
"yyyyMMdd"}
Dim cultureNames() As String = {"en-US", "fr-FR"}
Dim dat As New DateTime(2015, 8, 18, 13, 31, 17)
For Each cultureName In cultureNames
Dim culture As New CultureInfo(cultureName)
CultureInfo.CurrentCulture = culture
Console.WriteLine(culture.NativeName)
For Each fmt In formats
Console.WriteLine(" {0}: {1}", fmt,
dat.ToString(fmt))
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' English (United States)
' G: 8/18/2015 1:31:17 PM
' MM/yyyy: 08/2015
' MM\/dd\/yyyy HH:mm: 08/18/2015 13:31
' yyyyMMdd: 20150818
'
' français (France)
' G: 18/08/2015 13:31:17
' MM/yyyy: 08/2015
' MM\/dd\/yyyy HH:mm: 08/18/2015 13:31
' yyyyMMdd: 20150818
Note per i chiamanti
Il ToString(String) metodo restituisce la rappresentazione di stringa della data e dell'ora nel calendario utilizzato dalle impostazioni cultura correnti. Se il valore dell'istanza DateTime corrente è precedente o successivo a , il metodo genera MinSupportedDateTime MaxSupportedDateTime un'eccezione ArgumentOutOfRangeException . Nell'esempio seguente viene illustrato questo concetto. Tenta di formattare una data che non rientra nell'intervallo della classe quando le HebrewCalendar impostazioni cultura correnti sono ebraico (Alfabeto arabo).
using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(1550, 7, 21);
CultureInfo dft;
CultureInfo heIL = new CultureInfo("he-IL");
heIL.DateTimeFormat.Calendar = new HebrewCalendar();
// Change current culture to he-IL.
dft = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = heIL;
// Display the date using the current culture's calendar.
try {
Console.WriteLine(date1.ToString("G"));
}
catch (ArgumentOutOfRangeException) {
Console.WriteLine("{0} is earlier than {1} or later than {2}",
date1.ToString("d", CultureInfo.InvariantCulture),
heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture),
heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture));
}
// Restore the default culture.
Thread.CurrentThread.CurrentCulture = dft;
}
}
// The example displays the following output:
// 07/21/1550 is earlier than 01/01/1583 or later than 09/29/2239
Vedi anche
- DateTimeFormatInfo
- CultureInfo
- Formattazione di tipi in .NET
- Stringhe di formato di data e ora standard
- Stringhe di formato di data e ora personalizzato
Si applica a
ToString(IFormatProvider)
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando le informazioni sul formato relative alle impostazioni cultura specificate.
public:
virtual System::String ^ ToString(IFormatProvider ^ provider);
public:
System::String ^ ToString(IFormatProvider ^ provider);
public string ToString (IFormatProvider provider);
public string ToString (IFormatProvider? provider);
override this.ToString : IFormatProvider -> string
Public Function ToString (provider As IFormatProvider) As String
Parametri
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.
Restituisce
Rappresentazione di stringa del valore dell'oggetto DateTime corrente, come specificato da provider
.
Implementazioni
Eccezioni
La data e l'ora non sono comprese nell'intervallo di date supportato dal calendario usato da provider
.
Esempio
Nell'esempio seguente viene visualizzata la rappresentazione di stringa di una data e di un'ora CultureInfo utilizzando oggetti che rappresentano cinque impostazioni cultura diverse.
using System;
using System.Globalization;
public class Example2
{
public static void Main2()
{
CultureInfo[] cultures = new CultureInfo[] {CultureInfo.InvariantCulture,
new CultureInfo("en-us"),
new CultureInfo("fr-fr"),
new CultureInfo("de-DE"),
new CultureInfo("es-ES"),
new CultureInfo("ja-JP")};
DateTime thisDate = new DateTime(2009, 5, 1, 9, 0, 0);
foreach (CultureInfo culture in cultures)
{
string cultureName;
if (string.IsNullOrEmpty(culture.Name))
cultureName = culture.NativeName;
else
cultureName = culture.Name;
Console.WriteLine("In {0}, {1}",
cultureName, thisDate.ToString(culture));
}
}
}
// The example produces the following output:
// In Invariant Language (Invariant Country), 05/01/2009 09:00:00
// In en-US, 5/1/2009 9:00:00 AM
// In fr-FR, 01/05/2009 09:00:00
// In de-DE, 01.05.2009 09:00:00
// In es-ES, 01/05/2009 9:00:00
// In ja-JP, 2009/05/01 9:00:00
Imports System.Globalization
Module Example4
Public Sub Main4()
Dim cultures() As CultureInfo = {CultureInfo.InvariantCulture,
New CultureInfo("en-us"),
New CultureInfo("fr-fr"),
New CultureInfo("de-DE"),
New CultureInfo("es-ES"),
New CultureInfo("ja-JP")}
Dim thisDate As Date = #5/1/2009 9:00AM#
For Each culture As CultureInfo In cultures
Dim cultureName As String
If String.IsNullOrEmpty(culture.Name) Then
cultureName = culture.NativeName
Else
cultureName = culture.Name
End If
Console.WriteLine("In {0}, {1}",
cultureName, thisDate.ToString(culture))
Next
End Sub
End Module
' The example produces the following output:
' In Invariant Language (Invariant Country), 05/01/2009 09:00:00
' In en-US, 5/1/2009 9:00:00 AM
' In fr-FR, 01/05/2009 09:00:00
' In de-DE, 01.05.2009 09:00:00
' In es-ES, 01/05/2009 9:00:00
' In ja-JP, 2009/05/01 9:00:00
Commenti
Il valore dell'oggetto corrente viene formattato usando l'identificatore di formato di data e ora generale ('G'), che formatta l'output usando il modello di data breve e il modello DateTime di ora lunga.
Il formato del modello di data breve e ora lunga è definito dal provider
parametro . Il provider
parametro può essere uno dei seguenti:
Oggetto che rappresenta le impostazioni cultura le cui convenzioni di formattazione CultureInfo devono essere riflesse nella stringa restituita. DateTimeFormatInfoL'oggetto restituito CultureInfo.DateTimeFormat dalla proprietà definisce la formattazione della stringa restituita.
Oggetto DateTimeFormatInfo che definisce il formato dei dati di data e ora.
Oggetto personalizzato che implementa IFormatProvider l'interfaccia . Il GetFormat metodo restituisce un oggetto che fornisce informazioni di DateTimeFormatInfo formattazione.
Se provider
è , viene utilizzato null
DateTimeFormatInfo l'oggetto associato alle impostazioni cultura correnti. Per altre informazioni, vedere CultureInfo.CurrentCulture.
Note per i chiamanti
Il ToString(IFormatProvider) metodo restituisce la rappresentazione di stringa della data e dell'ora nel calendario utilizzato dalle impostazioni cultura rappresentate dal parametro provider
. Il calendario è definito dalla Calendar proprietà . Se il valore dell'istanza DateTime corrente è precedente o successivo a , il metodo genera MinSupportedDateTime MaxSupportedDateTime un'eccezione ArgumentOutOfRangeException . Nell'esempio seguente viene illustrato questo concetto. Tenta di formattare una data che non rientra nell'intervallo della JapaneseCalendar classe .
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
CultureInfo jaJP = new CultureInfo("ja-JP");
jaJP.DateTimeFormat.Calendar = new JapaneseCalendar();
DateTime date1 = new DateTime(1867, 1, 1);
try {
Console.WriteLine(date1.ToString(jaJP));
}
catch (ArgumentOutOfRangeException) {
Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}",
date1,
jaJP.DateTimeFormat.Calendar.MinSupportedDateTime,
jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime);
}
}
}
// The example displays the following output:
// 1/1/1867 is earlier than 9/8/1868 or later than 12/31/9999 }
Vedi anche
Si applica a
ToString()
Converte il valore dell'oggetto DateTime corrente nella rappresentazione di stringa equivalente, usando le convenzioni di formattazione delle impostazioni cultura.
public:
override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String
Restituisce
Rappresentazione di stringa del valore dell'oggetto DateTime corrente.
Eccezioni
La data e l'ora non sono comprese nell'intervallo di date supportato dal calendario usato dalle impostazioni cultura correnti.
Esempio
Nell'esempio seguente viene illustrato come la rappresentazione di stringa di un valore restituito dal metodo dipende DateTime dalle impostazioni cultura correnti del ToString() thread. Modifica le impostazioni cultura correnti in en-US, fr-FR e ja-JP e in ogni caso chiama il metodo per restituire la rappresentazione di stringa di un valore di data e ora usando tali ToString() impostazioni cultura.
using System;
using System.Globalization;
public class DateToStringExample
{
public static void Main()
{
CultureInfo currentCulture = CultureInfo.CurrentCulture;
DateTime exampleDate = new DateTime(2021, 5, 1, 18, 32, 6);
// Change the current culture to en-US and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(exampleDate.ToString());
// Change the current culture to fr-FR and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(exampleDate.ToString());
// Change the current culture to ja-JP and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ja-JP");
Console.WriteLine(exampleDate.ToString());
// Restore the original culture
CultureInfo.CurrentCulture = currentCulture;
}
}
// The example displays the following output to the console:
// 5/1/2021 6:32:06 PM
// 01/05/2021 18:32:06
// 2021/05/01 18:32:06
Imports System.Globalization
Module DateToStringExample
Public Sub Main()
Dim currentCulture As CultureInfo = CultureInfo.CurrentCulture
Dim exampleDate As Date = #05/01/2021 6:32:06PM#
' Change the current culture to en-US and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
Console.WriteLine(exampleDate.ToString())
' Change the current culture to fr-FR and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR")
Console.WriteLine(exampleDate.ToString())
' Change the current culture to ja-JP and display the date.
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ja-JP")
Console.WriteLine(exampleDate.ToString())
' Restore the original culture
CultureInfo.CurrentCulture = currentCulture
End Sub
End Module
' The example displays the following output to the console:
' 5/1/2021 6:32:06 PM
' 01/05/2021 18:32:06
' 2021/05/01 18:32:06
Commenti
Il valore dell'oggetto corrente viene formattato usando l'identificatore di formato di data e ora DateTime generale ('G'). Per formattarlo usando un identificatore di formato di data e ora specifico, chiamare il ToString(String) metodo . Per formattarlo usando l'identificatore di formato di data e ora generale ('G') per impostazioni cultura specifiche, chiamare il ToString(IFormatProvider) metodo . Per formattarlo usando un identificatore di formato di data e ora specifico e le convenzioni di impostazioni cultura specifiche, chiamare il ToString(String, IFormatProvider) metodo .
Questo metodo usa le informazioni di formattazione derivate dalle impostazioni cultura correnti. In particolare, combina le stringhe di formato personalizzate restituite dalle ShortDatePattern proprietà LongTimePattern e DateTimeFormatInfo dell'oggetto restituito dalla proprietà Thread.CurrentThread.CurrentCulture.DateTimeFormat
. Per altre informazioni, vedere CultureInfo.CurrentCulture. Altri overload del metodo consentono di specificare le impostazioni cultura di cui usare la formattazione e ToString di definire il modello di output del DateTime valore.
Note per i chiamanti
Il ToString() metodo restituisce la rappresentazione di stringa della data e dell'ora nel calendario utilizzato dalle impostazioni cultura correnti. Se il valore dell'istanza DateTime corrente è precedente o successivo a , il metodo genera MinSupportedDateTime MaxSupportedDateTime un'eccezione ArgumentOutOfRangeException . Nell'esempio seguente viene illustrato questo concetto. Tenta di formattare una data che non rientra nell'intervallo della classe quando le HijriCalendar impostazioni cultura correnti sono arabe (Alfabeto arabo).
using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(550, 1, 1);
CultureInfo dft;
CultureInfo arSY = new CultureInfo("ar-SY");
arSY.DateTimeFormat.Calendar = new HijriCalendar();
// Change current culture to ar-SY.
dft = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = arSY;
// Display the date using the current culture's calendar.
try {
Console.WriteLine(date1.ToString());
}
catch (ArgumentOutOfRangeException) {
Console.WriteLine("{0} is earlier than {1} or later than {2}",
date1.ToString("d", CultureInfo.InvariantCulture),
arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture),
arSY.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture));
}
// Restore the default culture.
Thread.CurrentThread.CurrentCulture = dft;
}
}
// The example displays the following output:
// 01/01/0550 is earlier than 07/18/0622 or later than 12/31/9999