DateTime.ToString Метод

Определение

Преобразует значение текущего объекта DateTime в эквивалентное ему строковое представление.

Перегрузки

ToString(IFormatProvider)

Преобразует значение текущего объекта DateTime в эквивалентное ему строковое представление с использованием указанных сведений о форматировании, связанных с языком и региональными параметрами.

ToString(String)

Преобразует значение текущего объекта DateTime в эквивалентное строковое представление с использованием указанного формата и соглашений о форматировании, принятых для текущего языка и региональных параметров.

ToString()

Преобразует значение текущего объекта DateTime в эквивалентное строковое представление с помощью соглашений о форматировании для текущего языка и региональных параметров.

ToString(String, IFormatProvider)

Преобразует значение текущего объекта DateTime в эквивалентное ему строковое представление с использованием указанного формата и сведений об особенностях формата для данного языка и региональных параметров.

ToString(IFormatProvider)

Преобразует значение текущего объекта DateTime в эквивалентное ему строковое представление с использованием указанных сведений о форматировании, связанных с языком и региональными параметрами.

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

Параметры

provider
IFormatProvider

Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.

Возвращаемое значение

Строковое представление значения текущего объекта DateTime, заданное параметром provider.

Реализации

Исключения

Дата и время находятся за пределами диапазона дат, поддерживаемого календарем, используемым в provider.

Примеры

В следующем примере отображается строковое представление даты и времени с помощью CultureInfo объектов, представляющих пять разных языков и региональных параметров.

using System;
using System.Globalization;

public class ToStringExample3
{
   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
open System
open System.Globalization

let cultures = 
    [ CultureInfo.InvariantCulture
      CultureInfo "en-us"
      CultureInfo "fr-fr"
      CultureInfo "de-DE"
      CultureInfo "es-ES"
      CultureInfo "ja-JP" ]

let thisDate = DateTime(2009, 5, 1, 9, 0, 0)

for culture in cultures do
    let cultureName =
        if String.IsNullOrEmpty culture.Name then
            culture.NativeName
        else
            culture.Name

    printfn $"In {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

Комментарии

Значение текущего DateTime объекта форматируется с помощью общего описателя формата даты и времени (G), который форматирует выходные данные с использованием шаблона короткой даты и длинного шаблона времени.

Формат шаблона короткой даты и длительного времени определяется параметром provider . Параметр provider может иметь любой из следующих значений:

  • Объект CultureInfo , представляющий язык и региональные параметры, соглашения о форматировании которых должны отражаться в возвращаемой строке. Объект DateTimeFormatInfo , возвращаемый свойством CultureInfo.DateTimeFormat , определяет форматирование возвращаемой строки.

  • Объект DateTimeFormatInfo , определяющий формат данных даты и времени.

  • Пользовательский объект, реализующий IFormatProvider интерфейс . Его GetFormat метод возвращает DateTimeFormatInfo объект , предоставляющий сведения о форматировании.

Если provider имеет значение null, используется объект , DateTimeFormatInfo связанный с текущим языком и региональными параметрами. Для получения дополнительной информации см. CultureInfo.CurrentCulture.

Примечания для тех, кто вызывает этот метод

Метод ToString(IFormatProvider) возвращает строковое представление даты и времени в календаре, используемом языком и региональными параметрами, представленными параметром provider . Его календарь определяется свойством Calendar . Если значение текущего DateTime экземпляра является более ранним или более поздним, чем MinSupportedDateTimeMaxSupportedDateTime, метод создает исключение ArgumentOutOfRangeException. Ниже приведен пример. Он пытается отформатировать дату, которая находится за пределами JapaneseCalendar диапазона класса .

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   }
open System
open System.Globalization

let jaJP = CultureInfo "ja-JP"
jaJP.DateTimeFormat.Calendar <- JapaneseCalendar()
let date1 = DateTime(1867, 1, 1)

try
    printfn $"{date1.ToString jaJP}"
with :? ArgumentOutOfRangeException ->
    printfn $"{date1:d} is earlier than {jaJP.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"

// The example displays the following output:
//    1/1/1867 is earlier than 9/8/1868 or later than 12/31/9999   }
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim jaJP As New CultureInfo("ja-JP")
      jaJP.DateTimeFormat.Calendar = New JapaneseCalendar() 
      Dim date1 As Date = #01/01/1867#

      Try
         Console.WriteLine(date1.ToString(jaJP))
      Catch e As ArgumentOutOfRangeException
         Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", _
                           date1, _
                           jaJP.DateTimeFormat.Calendar.MinSupportedDateTime, _ 
                           jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime) 
      End Try
   End Sub
End Module
' The example displays the following output:
'    1/1/1867 is earlier than 9/8/1868 or later than 12/31/9999

См. также раздел

Применяется к

ToString(String)

Преобразует значение текущего объекта DateTime в эквивалентное строковое представление с использованием указанного формата и соглашений о форматировании, принятых для текущего языка и региональных параметров.

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

Параметры

format
String

Строка стандартного или пользовательского формата даты и времени.

Возвращаемое значение

Строковое представление значения текущего объекта DateTime, заданное параметром format.

Исключения

Длина format равна 1, и он не является одним из символов описателя формата, определенного для DateTimeFormatInfo.

-или-

Параметр format не содержит допустимый пользовательский шаблон формата.

Дата и время находятся за пределами диапазона дат, поддерживаемого календарем, принятым для текущего языка и региональных параметров.

Примеры

В следующем примере используются все строки стандартного формата даты и времени, а также выбор настраиваемых строк формата даты и времени для отображения строкового DateTime представления значения. Текущий язык и региональные параметры потока для примера — en-US.

using System;

public class DateToStringExample2
{
   public static void Main()
   {
      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
open System

let dateValue = DateTime(2008, 6, 15, 21, 15, 07)
// Create a list of standard format strings.
let 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.
for standardFmt in standardFmts do
    printfn $"{standardFmt}: {dateValue.ToString standardFmt}"
printfn ""

// Create a list of some custom format strings.
let 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.
for customFmt in customFmts do
    printfn $"'{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

Комментарии

Метод ToString(String) возвращает строковое представление значения даты и времени в определенном формате, в котором используются соглашения о форматировании текущего языка и региональных параметров. Дополнительные сведения см. в разделе CultureInfo.CurrentCulture.

Параметр format должен содержать один описатель формата (см. раздел Стандартные строки формата даты и времени) или пользовательский шаблон формата (см. раздел Настраиваемые строки формата даты и времени), определяющий формат возвращаемой строки. Если format имеет значение null или является пустой строкой, используется описатель общего формата G.

Ниже приведены некоторые варианты использования этого метода.

  • Получение строки, отображающей дату и время в коротком формате даты и времени текущего языка и региональных параметров. Для этого используется описатель формата "G".

  • Получение строки, содержащей только месяц и год. Для этого используется строка формата "ММ/гггг". Строка формата использует разделитель даты для текущего языка и региональных параметров.

  • Получение строки, содержащей дату и время в определенном формате. Например, строка формата "ММ/дд/ггггЧ:мм" отображает строку даты и времени в фиксированном формате, например "19//03//2013 18:06". Строка формата использует "/" в качестве фиксированного разделителя даты независимо от параметров языка и региональных параметров.

  • Получение даты в сокращенном формате, который можно использовать для сериализации строки даты. Например, в строке формата "ггггММдд" отображается четырехзначный год, за которым следует двухзначный месяц и двухзначный день без разделителя даты.

В следующем примере эти три строки форматирования используются для отображения значения даты и времени с использованием соглашений о языках и региональных параметрах en-US и fr-FR.

using System;
using System.Globalization;

public class ToStringExample5
{
    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
open System
open System.Globalization

let formats = [ "G"; "MM/yyyy"; @"MM\/dd\/yyyy HH:mm"; "yyyyMMdd" ]
let cultureNames = [ "en-US"; "fr-FR" ]
let date = DateTime(2015, 8, 18, 13, 31, 17)
for cultureName in cultureNames do
    let culture = CultureInfo cultureName
    CultureInfo.CurrentCulture <- culture

    printfn $"{culture.NativeName}"
    for format in formats do
        printfn $"   {format}: {date.ToString format}"
    printfn ""

// 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

Примечания для тех, кто вызывает этот метод

Метод ToString(String) возвращает строковое представление даты и времени в календаре, используемом текущим языком и региональными параметрами. Если значение текущего DateTime экземпляра является более ранним или более поздним, чем MinSupportedDateTimeMaxSupportedDateTime, метод создает исключение ArgumentOutOfRangeException. Ниже приведен пример. Он пытается отформатировать дату, которая находится вне диапазона HebrewCalendar класса, если текущим языком и региональными параметрами является иврит (Израиль).

using System;
using System.Globalization;
using System.Threading;

public class Example3
{
    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
open System
open System.Globalization
open System.Threading

let date1 = DateTime(1550, 7, 21)
let heIL = CultureInfo "he-IL"
heIL.DateTimeFormat.Calendar <- HebrewCalendar()

// Change current culture to he-IL.
let dft = Thread.CurrentThread.CurrentCulture
Thread.CurrentThread.CurrentCulture <- heIL

// Display the date using the current culture's calendar.
try
    printfn $"{date1:G}"
with :? ArgumentOutOfRangeException ->
    printfn $"""{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {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
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim date1 As Date = #7/21/1550#
      Dim dft As CultureInfo
      Dim heIL As 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 e As 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)) 
      End Try
      
      ' Restore the default culture.
      Thread.CurrentThread.CurrentCulture = dft
   End Sub
End Module
' The example displays the following output:
'    07/21/1550 is earlier than 01/01/1583 or later than 09/29/2239

См. также раздел

Применяется к

ToString()

Преобразует значение текущего объекта DateTime в эквивалентное строковое представление с помощью соглашений о форматировании для текущего языка и региональных параметров.

public:
 override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String

Возвращаемое значение

Строковое представление значения текущего объекта DateTime.

Исключения

Дата и время находятся за пределами диапазона дат, поддерживаемого календарем, принятым для текущего языка и региональных параметров.

Примеры

В следующем примере показано, как строковое представление значения, возвращаемого DateTime методом ToString() , зависит от текущего языка и региональных параметров потока. Он изменяет текущий язык и региональные параметры на en-US, fr-FR и ja-JP и в каждом случае вызывает ToString() метод для возврата строкового представления значения даты и времени с помощью этого языка и региональных параметров.

using System;
using System.Globalization;

public class ToStringExample1
{
    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
open System
open System.Globalization

let currentCulture = CultureInfo.CurrentCulture
let exampleDate = DateTime(2021, 5, 1, 18, 32, 6)

// Change the current culture to en-US and display the date.
CultureInfo.CurrentCulture <- CultureInfo.GetCultureInfo "en-US"
printfn $"{exampleDate.ToString()}"

// Change the current culture to fr-FR and display the date.
CultureInfo.CurrentCulture <- CultureInfo.GetCultureInfo "fr-FR"
printfn $"{exampleDate.ToString()}"

// Change the current culture to ja-JP and display the date.
CultureInfo.CurrentCulture <- CultureInfo.GetCultureInfo "ja-JP"
printfn $"{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

Комментарии

Значение текущего DateTime объекта форматируется с помощью общего описателя формата даты и времени ('G'). Чтобы отформатировать его с помощью определенного описателя формата даты и времени, вызовите ToString(String) метод . Чтобы отформатировать его с помощью общего описатель формата даты и времени ('G') для определенного языка и региональных параметров, вызовите ToString(IFormatProvider) метод . Чтобы отформатировать его с помощью определенного описатель формата даты и времени и соглашений, относящихся к определенному языку ToString(String, IFormatProvider) и региональным параметрам, вызовите метод .

Этот метод использует сведения о форматировании, производные от текущего языка и региональных параметров. В частности, он объединяет строки настраиваемого формата, возвращаемые свойствами ShortDatePatternDateTimeFormatInfo и LongTimePattern объекта , возвращаемого свойством Thread.CurrentThread.CurrentCulture.DateTimeFormat . Для получения дополнительной информации см. CultureInfo.CurrentCulture. Другие перегрузки ToString метода позволяют указать язык и региональные параметры, форматирование которых следует использовать, и определить выходной DateTime шаблон значения.

Примечания для тех, кто вызывает этот метод

Метод ToString() возвращает строковое представление даты и времени в календаре, используемом текущим языком и региональными параметрами. Если значение текущего DateTime экземпляра является более ранним или более поздним, чем MinSupportedDateTimeMaxSupportedDateTime, метод создает исключение ArgumentOutOfRangeException. Ниже приведен пример. Он пытается отформатировать дату, которая находится за пределами HijriCalendar диапазона класса, если текущим языком и региональными параметрами является арабский (Сирия).

using System;
using System.Globalization;
using System.Threading;

public class Example2
{
    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
open System
open System.Globalization
open System.Threading

let date1 = DateTime(550, 1, 1)
let arSY = CultureInfo "ar-SY"
arSY.DateTimeFormat.Calendar <- HijriCalendar()

// Change current culture to ar-SY.
let dft = Thread.CurrentThread.CurrentCulture
Thread.CurrentThread.CurrentCulture <- arSY

// Display the date using the current culture's calendar.
try
    printfn $"{date1}"
with :? ArgumentOutOfRangeException ->
    printfn $"""{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {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
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Dim date1 As Date = #1/1/550#
      Dim dft As CultureInfo
      Dim arSY As 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 e As 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)) 
      End Try
      
      ' Restore the default culture.
      Thread.CurrentThread.CurrentCulture = dft
   End Sub
End Module
' The example displays the following output:
'    01/01/0550 is earlier than 07/18/0622 or later than 12/31/9999

См. также раздел

Применяется к

ToString(String, IFormatProvider)

Преобразует значение текущего объекта DateTime в эквивалентное ему строковое представление с использованием указанного формата и сведений об особенностях формата для данного языка и региональных параметров.

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

Параметры

format
String

Строка стандартного или пользовательского формата даты и времени.

provider
IFormatProvider

Объект, предоставляющий сведения о форматировании для определенного языка и региональных параметров.

Возвращаемое значение

Строковое представление значения текущего объекта DateTime, заданное параметрами format и provider.

Реализации

Исключения

Длина format равна 1, и он не является одним из символов описателя формата, определенного для DateTimeFormatInfo.

-или-

format не содержит допустимого шаблона пользовательского формата.

Дата и время находятся за пределами диапазона дат, поддерживаемого календарем, используемым в provider.

Примеры

В следующем примере каждая из строк стандартного формата даты и времени используется для отображения строкового представления даты и времени для четырех разных языков и региональных параметров.

using System;
using System.Globalization;

public class ToStringExample4
{
   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
open System
open System.Globalization

// Create a list of all supported standard date and time format specifiers.
let formats = 
    [ "d"; "D"; "f"; "F"; "g"; "G"; "m"; "o" 
      "r"; "s"; "t"; "T"; "u"; "U"; "Y" ]

// Create a list of four cultures.
let cultures = 
    [ CultureInfo.GetCultureInfo "de-DE"
      CultureInfo.GetCultureInfo "en-US"
      CultureInfo.GetCultureInfo "es-ES"
      CultureInfo.GetCultureInfo "fr-FR" ]

// Define date to be displayed.
let dateToDisplay = DateTime(2008, 10, 31, 17, 4, 32)

// Iterate each standard format specifier.
for formatSpecifier in formats do
    for culture in cultures do
        printfn $"{formatSpecifier} Format Specifier {culture.Name, 10} Culture {dateToDisplay.ToString(formatSpecifier, culture), 40}"
    printfn ""

// 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

В следующем примере показаны различные способы форматирования DateTime значения с помощью инвариантного 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
       */
}
open System
open System.Globalization

let dt = DateTime.Now
let formats =
    [ "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" ]

for format in formats do
    let date = dt.ToString(format, DateTimeFormatInfo.InvariantInfo)
    printfn $"{format}: {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

Комментарии

Параметр format может содержать один символ описателя формата (см. раздел Стандартные строки формата даты и времени) или пользовательский шаблон формата (см. раздел Настраиваемые строки формата даты и времени). Если format имеет значение null или является пустой строкой (""), используется описатель стандартного формата "G".

Параметр provider определяет шаблон, соответствующий описателям стандартного формата, а также символы и имена компонентов даты и времени. Параметр provider может иметь любой из следующих значений:

  • Объект CultureInfo , представляющий язык и региональные параметры, соглашения о форматировании которых должны отражаться в возвращаемой строке. Объект DateTimeFormatInfo , возвращаемый свойством CultureInfo.DateTimeFormat , определяет форматирование возвращаемой строки.

  • Объект DateTimeFormatInfo , определяющий формат данных даты и времени.

  • Пользовательский объект, реализующий IFormatProvider интерфейс . Его GetFormat метод возвращает DateTimeFormatInfo объект , предоставляющий сведения о форматировании.

Если provider имеет значение null, используется объект , DateTimeFormatInfo связанный с текущим языком и региональными параметрами. Для получения дополнительной информации см. CultureInfo.CurrentCulture.

Примечания для тех, кто вызывает этот метод

Метод ToString(String, IFormatProvider) возвращает строковое представление даты и времени в календаре, используемом параметром provider . Его календарь определяется свойством Calendar . Если значение текущего DateTime экземпляра является более ранним или более поздним, чем MinSupportedDateTimeMaxSupportedDateTime, метод создает исключение ArgumentOutOfRangeException. Ниже приведен пример. Он пытается отформатировать дату, которая находится за пределами UmAlQuraCalendar диапазона класса .

using System;
using System.Globalization;

public class Example4
{
    public static void Main()
    {
        CultureInfo arSA = new CultureInfo("ar-SA");
        arSA.DateTimeFormat.Calendar = new UmAlQuraCalendar();
        DateTime date1 = new DateTime(1890, 9, 10);

        try
        {
            Console.WriteLine(date1.ToString("d", arSA));
        }
        catch (ArgumentOutOfRangeException)
        {
            Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}",
                              date1,
                              arSA.DateTimeFormat.Calendar.MinSupportedDateTime,
                              arSA.DateTimeFormat.Calendar.MaxSupportedDateTime);
        }
    }
}
// The example displays the following output:
//    9/10/1890 is earlier than 4/30/1900 or later than 5/13/2029
open System
open System.Globalization

let arSA = CultureInfo "ar-SA"
arSA.DateTimeFormat.Calendar <- UmAlQuraCalendar()
let date1 = DateTime(1890, 9, 10)

try
    date1.ToString("d", arSA)
    |> printfn "%s"
with :? ArgumentOutOfRangeException ->
    printfn $"{date1:d} is earlier than {arSA.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {arSA.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"
                     
// The example displays the following output:
//    9/10/1890 is earlier than 4/30/1900 or later than 5/13/2029
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim arSA As New CultureInfo("ar-SA")
      arSA.DateTimeFormat.Calendar = New UmAlQuraCalendar() 
      Dim date1 As Date = #09/10/1890#

      Try
         Console.WriteLine(date1.ToString("d", arSA))
      Catch e As ArgumentOutOfRangeException
         Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", _
                           date1, _
                           arSA.DateTimeFormat.Calendar.MinSupportedDateTime, _ 
                           arSA.DateTimeFormat.Calendar.MaxSupportedDateTime) 
      End Try
   End Sub
End Module
' The example displays the following output:
'    9/10/1890 is earlier than 4/30/1900 or later than 5/13/2029

См. также раздел

Применяется к