Поделиться через


DateTimeOffset.ToString Метод

Определение

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

Перегрузки

ToString()

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

ToString(IFormatProvider)

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

ToString(String)

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

ToString(String, IFormatProvider)

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

ToString()

Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs

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

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

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

Строковое представление объекта DateTimeOffset, которое включает смещение, добавленное в конце строки.

Исключения

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

Примеры

В следующем примере показаны вызовы ToString() метода и его выходные данные в системе с текущим языком и региональными параметрами en-us.

DateTimeOffset thisDate;

// Show output for UTC time
thisDate = DateTimeOffset.UtcNow;
Console.WriteLine(thisDate.ToString());  // Displays 3/28/2007 7:13:50 PM +00:00

// Show output for local time
thisDate = DateTimeOffset.Now;
Console.WriteLine(thisDate.ToString());  // Displays 3/28/2007 12:13:50 PM -07:00

// Show output for arbitrary time offset
thisDate = thisDate.ToOffset(new TimeSpan(-5, 0, 0));
Console.WriteLine(thisDate.ToString());  // Displays 3/28/2007 2:13:50 PM -05:00
// Show output for UTC time
let thisDate = DateTimeOffset.UtcNow
printfn $"{thisDate.ToString()}"  // Displays 3/28/2007 7:13:50 PM +00:00

// Show output for local time
let thisDate = DateTimeOffset.Now
printfn $"{thisDate.ToString()}"  // Displays 3/28/2007 12:13:50 PM -07:00

// Show output for arbitrary time offset
let thisDate = thisDate.ToOffset(TimeSpan(-5, 0, 0))
printfn $"{thisDate.ToString()}"  // Displays 3/28/2007 2:13:50 PM -05:00
Dim thisDate As DateTimeOffset

' Show output for UTC time
thisDate = DateTimeOffset.UtcNow
Console.WriteLine(thisDate.ToString())  ' Displays 3/28/2007 7:13:50 PM +00:00

' Show output for local time 
thisDate = DateTimeOffset.Now
Console.WriteLine(thisDate.ToString())  ' Displays 3/28/2007 12:13:50 PM -07:00

' Show output for arbitrary time offset
thisDate = thisDate.ToOffset(new TimeSpan(-5, 0, 0))
Console.WriteLine(thisDate.ToString())  ' Displays 3/28/2007 2:13:50 PM -05:00

Комментарии

Возвращаемое значение этого метода идентично значению DateTime.ToString() метода, за исключением того, что он включает пробел, за которым следует смещение, добавленное в конце строки. Другими словами, он форматирует выходные данные, используя короткий шаблон даты, длинный шаблон времени и zzz строку настраиваемого формата, при этом каждый элемент отделен от предыдущего элемента пробелом. Например, если DateTime.ToString() возвращает значение 12.01.2008 18:15:50, ToString() возвращается значение 12.01.2008 18:15:50–08:00 для времени, которое на восемь часов отстает от времени utc.

Этот метод использует сведения о форматировании, производные от текущего языка и региональных параметров. Для получения дополнительной информации см. CurrentCulture. Другие перегрузки ToString метода позволяют указать язык и региональные параметры, форматирование которых следует использовать, и определить выходной DateTimeOffset шаблон значения.

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

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

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

public class Example
{
   public static void Main()
   {
      DateTimeOffset date1 = new DateTimeOffset(new DateTime(550, 1, 1),
                                                TimeSpan.Zero);
      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 = DateTimeOffset(DateTime(550, 1, 1), TimeSpan.Zero)

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 New DateTimeOffset(#1/1/550#, TimeSpan.Zero)
      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:d} or later than {2:d}", _
                           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(IFormatProvider)

Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs

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

public:
 System::String ^ ToString(IFormatProvider ^ formatProvider);
public string ToString (IFormatProvider formatProvider);
public string ToString (IFormatProvider? formatProvider);
override this.ToString : IFormatProvider -> string
Public Function ToString (formatProvider As IFormatProvider) As String

Параметры

formatProvider
IFormatProvider

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

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

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

Исключения

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

Примеры

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

CultureInfo[] cultures = new CultureInfo[] {CultureInfo.InvariantCulture,
                                           new CultureInfo("en-us"),
                                           new CultureInfo("fr-fr"),
                                           new CultureInfo("de-DE"),
                                           new CultureInfo("es-ES")};

DateTimeOffset thisDate = new DateTimeOffset(2007, 5, 1, 9, 0, 0,
                                             TimeSpan.Zero);

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/2007 09:00:00 +00:00
//    In en-US, 5/1/2007 9:00:00 AM +00:00
//    In fr-FR, 01/05/2007 09:00:00 +00:00
//    In de-DE, 01.05.2007 09:00:00 +00:00
//    In es-ES, 01/05/2007 9:00:00 +00:00
let cultures = 
    [| CultureInfo.InvariantCulture
       CultureInfo "en-us"
       CultureInfo "fr-fr"
       CultureInfo "de-DE"
       CultureInfo "es-ES" |]

let thisDate = DateTimeOffset(2007, 5, 1, 9, 0, 0, TimeSpan.Zero)

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/2007 09:00:00 +00:00
//    In en-US, 5/1/2007 9:00:00 AM +00:00
//    In fr-FR, 01/05/2007 09:00:00 +00:00
//    In de-DE, 01.05.2007 09:00:00 +00:00
//    In es-ES, 01/05/2007 9:00:00 +00:00
     Dim cultures() As CultureInfo = {CultureInfo.InvariantCulture, _
                                      New CultureInfo("en-us"), _
                                      New CultureInfo("fr-fr"), _
                                      New CultureInfo("de-DE"), _
                                      New CultureInfo("es-ES")}

     Dim thisDate As New DateTimeOffset(#5/1/2007 9:00AM#, TimeSpan.Zero)                                            

     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                                            
     ' The example produces the following output:
     '    In Invariant Language (Invariant Country), 05/01/2007 09:00:00 +00:00
     '    In en-US, 5/1/2007 9:00:00 AM +00:00
     '    In fr-FR, 01/05/2007 09:00:00 +00:00
     '    In de-DE, 01.05.2007 09:00:00 +00:00
     '    In es-ES, 01/05/2007 9:00:00 +00:00

Комментарии

Возвращаемое значение этого метода идентично значению эквивалентной перегрузки DateTime.ToString метода, за исключением того, что он включает пробел, за которым следует смещение, добавленное в конце строки. Другими словами, он форматирует выходные данные, используя короткий шаблон даты, длинный шаблон времени и zzz строку настраиваемого формата, при этом каждый элемент отделен от предыдущего элемента пробелом.

Формат этих трех элементов определяется параметром formatProvider . Параметр formatProvider может иметь один из следующих значений:

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

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

Если formatProvider имеет значение null, используется объект , DateTimeFormatInfo связанный с текущим языком и региональными параметрами (см. ).CurrentCulture

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

Метод ToString(IFormatProvider) возвращает строковое представление даты и времени в календаре, используемом языком и региональными параметрами, представленными параметром formatProvider . Его календарь определяется свойством Calendar . Если значение текущего DateTimeOffset экземпляра раньше MinSupportedDateTime или позже MaxSupportedDateTime, метод создает исключение 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();
      DateTimeOffset date1 = new DateTimeOffset(new DateTime(1867, 1, 1),
                                                TimeSpan.Zero);

      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 = DateTimeOffset(DateTime(1867, 1, 1), TimeSpan.Zero)

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 New DateTimeOffset(#01/01/1867#, TimeSpan.Zero)

      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)

Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs

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

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

Строка формата.

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

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

Исключения

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

-или-

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

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

Примеры

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

DateTimeOffset outputDate = new DateTimeOffset(2007, 10, 31, 21, 0, 0,
                                     new TimeSpan(-8, 0, 0));
string specifier;

// Output date using each standard date/time format specifier
specifier = "d";
// Displays   d: 10/31/2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "D";
// Displays   D: Wednesday, October 31, 2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "t";
// Displays   t: 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "T";
// Displays   T: 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "f";
// Displays   f: Wednesday, October 31, 2007 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "F";
// Displays   F: Wednesday, October 31, 2007 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "g";
// Displays   g: 10/31/2007 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "G";
// Displays   G: 10/31/2007 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "M";           // 'm' is identical
// Displays   M: October 31
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "R";           // 'r' is identical
// Displays   R: Thu, 01 Nov 2007 05:00:00 GMT
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "s";
// Displays   s: 2007-10-31T21:00:00
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

specifier = "u";
// Displays   u: 2007-11-01 05:00:00Z
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));

// Specifier is not supported
specifier = "U";
try
{
   Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));
}
catch (FormatException)
{
   Console.WriteLine("{0}: Not supported.", specifier);
}

specifier = "Y";         // 'y' is identical
// Displays   Y: October, 2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier));
let outputDate = DateTimeOffset(2007, 10, 31, 21, 0, 0, TimeSpan(-8, 0, 0))

// Output date using each standard date/time format specifier
let specifier = "d"
// Displays   d: 10/31/2007
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "D"
// Displays   D: Wednesday, October 31, 2007
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "t"
// Displays   t: 9:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "T"
// Displays   T: 9:00:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "f"
// Displays   f: Wednesday, October 31, 2007 9:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "F"
// Displays   F: Wednesday, October 31, 2007 9:00:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "g"
// Displays   g: 10/31/2007 9:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "G"
// Displays   G: 10/31/2007 9:00:00 PM
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "M"           // 'm' is identical
// Displays   M: October 31
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "R"           // 'r' is identical
// Displays   R: Thu, 01 Nov 2007 05:00:00 GMT
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "s"
// Displays   s: 2007-10-31T21:00:00
printfn $"{specifier}: {outputDate.ToString specifier}"

let specifier = "u"
// Displays   u: 2007-11-01 05:00:00Z
printfn $"{specifier}: {outputDate.ToString specifier}"

// Specifier is not supported
let specifier = "U"
try
    printfn $"{specifier}: {outputDate.ToString specifier}"
with :? FormatException ->
    printfn $"{specifier}: Not supported."

let specifier = "Y"         // 'y' is identical
// Displays   Y: October, 2007
printfn $"{specifier}: {outputDate.ToString specifier}"
Dim outputDate As New DateTimeOffset(#10/31/2007 9:00PM#, _
                                     New TimeSpan(-8, 0, 0))
Dim specifier As String 
      
' Output date using each standard date/time format specifier
specifier = "d"
' Displays   d: 10/31/2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "D"
' Displays   D: Wednesday, October 31, 2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "t"
' Displays   t: 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "T"
' Displays   T: 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "f"
' Displays   f: Wednesday, October 31, 2007 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "F"
' Displays   F: Wednesday, October 31, 2007 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "g"
' Displays   g: 10/31/2007 9:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "G"
' Displays   G: 10/31/2007 9:00:00 PM
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "M"           ' 'm' is identical
' Displays   M: October 31
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "R"           ' 'r' is identical
' Displays   R: Thu, 01 Nov 2007 05:00:00 GMT
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "s"
' Displays   s: 2007-10-31T21:00:00
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

specifier = "u"
' Displays   u: 2007-11-01 05:00:00Z
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 

' Specifier is not supported
specifier = "U"
Try
   Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)) 
Catch e As FormatException
   Console.WriteLine("{0}: Not supported.", specifier)   
End Try

specifier = "Y"         ' 'y' is identical
' Displays   Y: October, 2007
Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier))

Комментарии

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

В следующей таблице показана точная операция определенных описателей формата при использовании с DateTimeOffset, которая отличается от их поведения при использовании с DateTime.

Существующий описатель формата Новое поведение
"K" Предназначен для кругового пути даты и времени. При использовании DateTimeOffsetсопоставляется с zzz (смещение всегда отображается с часами и минутами). Обратите внимание, что "K" является настраиваемым описателем формата; Он не может отображаться в виде одного символа в format.
"U" Не поддерживается.
"r" Преобразует объект в DateTimeOffset формат UTC и выводит его с помощью строки ddd, dd MMM yyyy HH:mm:ss GMTнастраиваемого формата .
"u" Преобразует объект в DateTimeOffset формат UTC и выводит его в формате yyyy-MM-dd HH:mm:ssZ.

Остальные стандартные описатели формата даты и времени ведут себя так же, ToString(String) как и с методом ToString .

Этот метод использует сведения о форматировании, производные от текущего языка и региональных параметров. Для получения дополнительной информации см. CurrentCulture.

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

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

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

public class Example
{
   public static void Main()
   {
      DateTimeOffset date1 = new DateTimeOffset(new DateTime(1550, 7, 21),
                                                TimeSpan.Zero);
      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 = DateTimeOffset(DateTime(1550, 7, 21), TimeSpan.Zero)

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 New DateTimeOffset(#7/21/1550#, TimeSpan.Zero)
      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(String, IFormatProvider)

Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs
Исходный код:
DateTimeOffset.cs

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

public:
 virtual System::String ^ ToString(System::String ^ format, IFormatProvider ^ formatProvider);
public string ToString (string format, IFormatProvider formatProvider);
public string ToString (string? format, IFormatProvider? formatProvider);
override this.ToString : string * IFormatProvider -> string
Public Function ToString (format As String, formatProvider As IFormatProvider) As String

Параметры

format
String

Строка формата.

formatProvider
IFormatProvider

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

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

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

Реализации

Исключения

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

-или-

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

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

Примеры

В следующем примере метод используется ToString(String, IFormatProvider) для отображения DateTimeOffset объекта с помощью строки настраиваемого формата для нескольких различных языков и региональных параметров.

DateTimeOffset outputDate = new DateTimeOffset(2007, 11, 1, 9, 0, 0,
                                     new TimeSpan(-7, 0, 0));
string format = "dddd, MMM dd yyyy HH:mm:ss zzz";

// Output date and time using custom format specification
Console.WriteLine(outputDate.ToString(format, null as DateTimeFormatInfo));
Console.WriteLine(outputDate.ToString(format, CultureInfo.InvariantCulture));
Console.WriteLine(outputDate.ToString(format,
                                      new CultureInfo("fr-FR")));
Console.WriteLine(outputDate.ToString(format,
                                      new CultureInfo("es-ES")));
// The example displays the following output to the console:
//    Thursday, Nov 01 2007 09:00:00 -07:00
//    Thursday, Nov 01 2007 09:00:00 -07:00
//    jeudi, nov. 01 2007 09:00:00 -07:00
//    jueves, nov 01 2007 09:00:00 -07:00
let outputDate = DateTimeOffset(2007, 11, 1, 9, 0, 0, TimeSpan(-7, 0, 0))
let format = "dddd, MMM dd yyyy HH:mm:ss zzz"

// Output date and time using custom format specification
printfn $"{outputDate.ToString(format, null)}"
printfn $"{outputDate.ToString(format, CultureInfo.InvariantCulture)}"
printfn $"""{outputDate.ToString(format, CultureInfo "fr-FR")}"""
printfn $"""{outputDate.ToString(format, CultureInfo "es-ES")}"""

// The example displays the following output to the console:
//    Thursday, Nov 01 2007 09:00:00 -07:00
//    Thursday, Nov 01 2007 09:00:00 -07:00
//    jeudi, nov. 01 2007 09:00:00 -07:00
//    jueves, nov 01 2007 09:00:00 -07:00
Dim outputDate As New DateTimeOffset(#11/1/2007 9:00AM#, _
                                     New TimeSpan(-7, 0, 0)) 
Dim format As String = "dddd, MMM dd yyyy HH:mm:ss zzz"

' Output date and time using custom format specification
Console.WriteLine(outputDate.ToString(format, Nothing))
Console.WriteLine(outputDate.ToString(format, CultureInfo.InvariantCulture))
Console.WriteLine(outputDate.ToString(format, _
                                      New CultureInfo("fr-FR")))
Console.WriteLine(outputDate.ToString(format, _
                                      New CultureInfo("es-ES")))
' The example displays the following output to the console:
'    Thursday, Nov 01 2007 09:00:00 -07:00
'    Thursday, Nov 01 2007 09:00:00 -07:00
'    jeudi, nov. 01 2007 09:00:00 -07:00
'    jueves, nov 01 2007 09:00:00 -07:00

Комментарии

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

В следующей таблице показана точная операция определенных описателей формата при использовании с DateTimeOffset, которая отличается от их поведения при использовании с DateTime.

Существующий описатель формата Новое поведение
"K" Предназначен для кругового пути даты и времени. При использовании DateTimeOffsetсопоставляется с zzz (смещение всегда отображается с часами и минутами). Обратите внимание, что "K" является настраиваемым описателем формата; Он не может отображаться в виде одного символа в format.
"U" Не поддерживается.
"r" Преобразует объект в DateTimeOffset формат UTC и выводит его с помощью строки ddd, dd MMM yyyy HH:mm:ss GMTнастраиваемого формата .
"u" Преобразует значение в DateTimeOffset формат UTC и выводит его в формате yyyy-MM-dd HH:mm:ssZ.

Остальные стандартные описатели формата даты и времени ведут себя так же, ToString(String) как и с методом ToString .

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

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

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

Если formatProvider имеет значение null, используется объект , DateTimeFormatInfo связанный с текущим языком и региональными параметрами (см. ).CurrentCulture

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

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

using System;
using System.Globalization;

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

      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 = DateTimeOffset(DateTime(1890, 9, 10), TimeSpan.Zero)

try
    printfn $"""{date1.ToString("d", arSA)}"""
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 11/16/2077
Imports System.Globalization

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

      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

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

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