Tworzenie wystąpień obiektów DateTimeOffset

Struktura DateTimeOffset oferuje wiele sposobów tworzenia nowych DateTimeOffset wartości. Wiele z nich odpowiada bezpośrednio metodom dostępnym do tworzenia wystąpień nowych DateTime wartości z ulepszeniami, które umożliwiają określenie przesunięcia wartości daty i godziny z uniwersalnego czasu koordynowanego (UTC). W szczególności można utworzyć wystąpienie DateTimeOffset wartości w następujący sposób:

  • Używając literału daty i godziny.

  • Wywołując DateTimeOffset konstruktor.

  • Niejawnie konwertując wartość na DateTimeOffset wartość.

  • Przeanalizuj ciąg reprezentujący datę i godzinę.

Ten temat zawiera bardziej szczegółowe informacje i przykłady kodu ilustrujące te metody tworzenia wystąpień nowych DateTimeOffset wartości.

Literały daty i godziny

W przypadku języków, które go obsługują, jednym z najczęstszych sposobów utworzenia wystąpienia DateTime wartości jest podanie daty i godziny jako zakodowanej wartości literału. Na przykład poniższy kod języka Visual Basic tworzy DateTime obiekt, którego wartość to 1 maja 2008 r., o godzinie 8:06:32.

Dim literalDate1 As Date = #05/01/2008 8:06:32 AM#
Console.WriteLine(literalDate1.ToString())
' Displays:
'              5/1/2008 8:06:32 AM

DateTimeOffset wartości mogą być również inicjowane przy użyciu literałów daty i godziny w przypadku używania języków obsługujących DateTime literały. Na przykład poniższy kod języka Visual Basic tworzy DateTimeOffset obiekt.

Dim literalDate As DateTimeOffset = #05/01/2008 8:06:32 AM#
Console.WriteLine(literalDate.ToString())
' Displays:
'              5/1/2008 8:06:32 AM -07:00

Jak pokazuje dane wyjściowe konsoli, DateTimeOffset wartość utworzona w ten sposób jest przypisywana przesunięcie lokalnej strefy czasowej. Oznacza to, że wartość przypisana DateTimeOffset przy użyciu literału znaku nie identyfikuje pojedynczego punktu czasu, jeśli kod jest uruchamiany na różnych komputerach.

Konstruktory DateTimeOffset

Typ DateTimeOffset definiuje sześć konstruktorów. Cztery z nich odpowiadają bezpośrednio DateTime konstruktorom, z dodatkowym parametrem typu TimeSpan definiującym przesunięcie daty i godziny z czasu UTC. Umożliwiają one zdefiniowanie DateTimeOffset wartości na podstawie wartości poszczególnych składników daty i godziny. Na przykład poniższy kod używa tych czterech konstruktorów do tworzenia wystąpień DateTimeOffset obiektów o identycznych wartościach 5/1/2008 8:06:32 +01:00.

DateTimeOffset dateAndTime;

// Instantiate date and time using years, months, days,
// hours, minutes, and seconds
dateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32,
                                 new TimeSpan(1, 0, 0));
Console.WriteLine(dateAndTime);
// Instantiate date and time using years, months, days,
// hours, minutes, seconds, and milliseconds
dateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32, 545,
                                 new TimeSpan(1, 0, 0));
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"),
                             dateAndTime.ToString("zzz"));

// Instantiate date and time using Persian calendar with years,
// months, days, hours, minutes, seconds, and milliseconds
dateAndTime = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545,
                                 new PersianCalendar(),
                                 new TimeSpan(1, 0, 0));
// Note that the console output displays the date in the Gregorian
// calendar, not the Persian calendar.
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"),
                             dateAndTime.ToString("zzz"));

// Instantiate date and time using number of ticks
// 05/01/2008 8:06:32 AM is 633,452,259,920,000,000 ticks
dateAndTime = new DateTimeOffset(633452259920000000, new TimeSpan(1, 0, 0));
Console.WriteLine(dateAndTime);
// The example displays the following output to the console:
//       5/1/2008 8:06:32 AM +01:00
//       5/1/2008 8:06:32 AM +01:00
//       5/1/2008 8:06:32 AM +01:00
//       5/1/2008 8:06:32 AM +01:00
Dim dateAndTime As DateTimeOffset

' Instantiate date and time using years, months, days, 
' hours, minutes, and seconds
dateAndTime = New DateTimeOffset(2008, 5, 1, 8, 6, 32, _
                                 New TimeSpan(1, 0, 0))
Console.WriteLine(dateAndTime)
' Instantiate date and time using years, months, days,
' hours, minutes, seconds, and milliseconds
dateAndTime = New DateTimeOffset(2008, 5, 1, 8, 6, 32, 545, _
                                 New TimeSpan(1, 0, 0))
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"), _
                             dateAndTime.ToString("zzz"))

' Instantiate date and time using Persian calendar with years,
' months, days, hours, minutes, seconds, and milliseconds
dateAndTime = New DateTimeOffset(1387, 2, 12, 8, 6, 32, 545, New PersianCalendar, New TimeSpan(1, 0, 0))
' Note that the console output displays the date in the Gregorian
' calendar, not the Persian calendar. 
Console.WriteLine("{0} {1}", dateAndTime.ToString("G"), _
                             dateAndTime.ToString("zzz"))

' Instantiate date and time using number of ticks
' 05/01/2008 8:06:32 AM is 633,452,259,920,000,000 ticks
dateAndTime = New DateTimeOffset(633452259920000000, New TimeSpan(1, 0, 0))
Console.WriteLine(dateAndTime)
' The example displays the following output to the console:
'       5/1/2008 8:06:32 AM +01:00
'       5/1/2008 8:06:32 AM +01:00
'       5/1/2008 8:06:32 AM +01:00
'       5/1/2008 8:06:32 AM +01:00

Należy pamiętać, że gdy wartość DateTimeOffset obiektu utworzonego PersianCalendar przy użyciu obiektu jako jeden z argumentów konstruktora jest wyświetlana w konsoli, jest wyrażona jako data w kalendarzu gregoriańskim, a nie w kalendarzu perskim. Aby wyświetlić datę przy użyciu kalendarza perskiego, zobacz przykład w temacie PersianCalendar .

Dwa pozostałe konstruktory tworzą DateTimeOffset obiekt na podstawie DateTime wartości. Pierwszy z nich ma jeden parametr, czyli wartość, DateTime która ma być konwertowana DateTimeOffset na wartość. Przesunięcie wartości wynikowej DateTimeOffset zależy Kind od właściwości pojedynczego parametru konstruktora. Jeśli jego wartość to DateTimeKind.Utc, przesunięcie jest ustawione na TimeSpan.Zerowartość . W przeciwnym razie jego przesunięcie jest ustawione na wartość równą lokalnej strefie czasowej. Poniższy przykład ilustruje użycie tego konstruktora do tworzenia wystąpień DateTimeOffset obiektów reprezentujących utc i lokalną strefę czasową:

// Declare date; Kind property is DateTimeKind.Unspecified
DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
DateTimeOffset targetTime;

// Instantiate a DateTimeOffset value from a UTC time
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = new DateTimeOffset(utcTime);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the offset is TimeSpan.Zero.

// Instantiate a DateTimeOffset value from a UTC time with a zero offset
targetTime = new DateTimeOffset(utcTime, TimeSpan.Zero);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the call to the constructor succeeds

// Instantiate a DateTimeOffset value from a UTC time with a negative offset
try
{
   targetTime = new DateTimeOffset(utcTime, new TimeSpan(-2, 0, 0));
   Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
   Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
                      targetTime);
}
// Throws exception and displays the following to the console:
//   Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM +00:00 failed.

// Instantiate a DateTimeOffset value from a local time
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = new DateTimeOffset(localTime);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Local,
// the offset is that of the local time zone.

// Instantiate a DateTimeOffset value from an unspecified time
targetTime = new DateTimeOffset(sourceDate);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Unspecified,
// the offset is that of the local time zone.
' Declare date; Kind property is DateTimeKind.Unspecified
Dim sourceDate As Date = #5/1/2008 8:30 AM#
Dim targetTime As DateTimeOffset

' Instantiate a DateTimeOffset value from a UTC time 
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = New DateTimeOffset(utcTime)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00
' Because the Kind property is DateTimeKind.Utc, 
' the offset is TimeSpan.Zero.


' Instantiate a DateTimeOffset value from a local time
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = New DateTimeOffset(localTime)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
' Because the Kind property is DateTimeKind.Local, 
' the offset is that of the local time zone.

' Instantiate a DateTimeOffset value from an unspecified time
targetTime = New DateTimeOffset(sourceDate)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00
' Because the Kind property is DateTimeKind.Unspecified, 
' the offset is that of the local time zone.

'

Uwaga

Wywoływanie przeciążenia konstruktora DateTimeOffset , który ma pojedynczy DateTime parametr, jest równoważne wykonaniu niejawnej konwersji DateTime wartości na DateTimeOffset wartość.

Drugi konstruktor tworzący DateTimeOffset obiekt na podstawie DateTime wartości ma dwa parametry: DateTime wartość do przekonwertowania i wartość reprezentującą TimeSpan przesunięcie daty i godziny z utc. Ta wartość przesunięcia musi odpowiadać Kind właściwości pierwszego parametru konstruktora lub ArgumentException jest zgłaszana. Kind Jeśli właściwość pierwszego parametru to DateTimeKind.Utc, wartość drugiego parametru musi mieć wartość TimeSpan.Zero. Kind Jeśli właściwość pierwszego parametru to DateTimeKind.Local, wartość drugiego parametru musi być przesunięciem strefy czasowej systemu lokalnego. Kind Jeśli właściwość pierwszego parametru to DateTimeKind.Unspecified, przesunięcie może być dowolną prawidłową wartością. Poniższy kod ilustruje wywołania tego konstruktora w celu przekonwertowania DateTime na DateTimeOffset wartości.

DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
DateTimeOffset targetTime;

// Instantiate a DateTimeOffset value from a UTC time with a zero offset.
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = new DateTimeOffset(utcTime, TimeSpan.Zero);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00
// Because the Kind property is DateTimeKind.Utc,
// the call to the constructor succeeds

// Instantiate a DateTimeOffset value from a UTC time with a non-zero offset.
try
{
   targetTime = new DateTimeOffset(utcTime, new TimeSpan(-2, 0, 0));
   Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
   Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
                      utcTime);
}
// Throws exception and displays the following to the console:
//   Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.

// Instantiate a DateTimeOffset value from a local time with
// the offset of the local time zone
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = new DateTimeOffset(localTime,
                                TimeZoneInfo.Local.GetUtcOffset(localTime));
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
// Because the Kind property is DateTimeKind.Local and the offset matches
// that of the local time zone, the call to the constructor succeeds.

// Instantiate a DateTimeOffset value from a local time with a zero offset.
try
{
   targetTime = new DateTimeOffset(localTime, TimeSpan.Zero);
   Console.WriteLine(targetTime);
}
catch (ArgumentException)
{
   Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.",
                      localTime);
}
// Throws exception and displays the following to the console:
//   Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.

// Instantiate a DateTimeOffset value with an arbitrary time zone.
string timeZoneName = "Central Standard Time";
TimeSpan offset = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).
                         GetUtcOffset(sourceDate);
targetTime = new DateTimeOffset(sourceDate, offset);
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -05:00
Dim sourceDate As Date = #5/1/2008 8:30 AM#
Dim targetTime As DateTimeOffset

' Instantiate a DateTimeOffset value from a UTC time with a zero offset.
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = New DateTimeOffset(utcTime, TimeSpan.Zero)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00
' Because the Kind property is DateTimeKind.Utc,  
' the call to the constructor succeeds.

' Instantiate a DateTimeOffset value from a UTC time with a non-zero offset.
Try
    targetTime = New DateTimeOffset(utcTime, New TimeSpan(-2, 0, 0))
    Console.WriteLine(targetTime)
Catch e As ArgumentException
    Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", _
                       utcTime)
End Try
' Throws exception and displays the following to the console:
'   Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.

' Instantiate a DateTimeOffset value from a local time with 
' the offset of the local time zone.
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = New DateTimeOffset(localTime, _
                                TimeZoneInfo.Local.GetUtcOffset(localTime))
Console.WriteLine(targetTime)
' Because the Kind property is DateTimeKind.Local and the offset matches
' that of the local time zone, the call to the constructor succeeds.

' Instantiate a DateTimeOffset value from a local time with a zero offset.
Try
    targetTime = New DateTimeOffset(localTime, TimeSpan.Zero)
    Console.WriteLine(targetTime)
Catch e As ArgumentException
    Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", _
                       localTime)
End Try
' Throws exception and displays the following to the console:
'   Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed.

' Instantiate a DateTimeOffset value with an arbitrary time zone.
Dim timeZoneName As String = "Central Standard Time"
Dim offset As TimeSpan = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName). _
                         GetUtcOffset(sourceDate)
targetTime = New DateTimeOffset(sourceDate, offset)
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -05:00

Niejawna konwersja typu

Typ DateTimeOffset obsługuje jedną niejawną konwersję DateTimeDateTimeOffset typu: od wartości do wartości. (Niejawna konwersja typu to konwersja z jednego typu na inny, która nie wymaga jawnego rzutowania (w języku C#) ani konwersji (w Visual Basic) i nie powoduje utraty informacji. Dzięki temu kod jest podobny do poniższego.

DateTimeOffset targetTime;

// The Kind property of sourceDate is DateTimeKind.Unspecified
DateTime sourceDate = new DateTime(2008, 5, 1, 8, 30, 0);
targetTime = sourceDate;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00

// define a UTC time (Kind property is DateTimeKind.Utc)
DateTime utcTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Utc);
targetTime = utcTime;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM +00:00

// Define a local time (Kind property is DateTimeKind.Local)
DateTime localTime = DateTime.SpecifyKind(sourceDate, DateTimeKind.Local);
targetTime = localTime;
Console.WriteLine(targetTime);
// Displays 5/1/2008 8:30:00 AM -07:00
Dim targetTime As DateTimeOffset

' The Kind property of sourceDate is DateTimeKind.Unspecified
Dim sourceDate As Date = #5/1/2008 8:30 AM#
targetTime = sourceDate
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00

' define a UTC time (Kind property is DateTimeKind.Utc)
Dim utcTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Utc)
targetTime = utcTime
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM +00:00

' Define a local time (Kind property is DateTimeKind.Local)
Dim localTime As Date = Date.SpecifyKind(sourceDate, DateTimeKind.Local)
targetTime = localTime
Console.WriteLine(targetTime)
' Displays 5/1/2008 8:30:00 AM -07:00

Przesunięcie wartości wynikowej DateTimeOffset zależy DateTime.Kind od wartości właściwości. Jeśli jego wartość to DateTimeKind.Utc, przesunięcie jest ustawione na TimeSpan.Zerowartość . Jeśli jego wartość to DateTimeKind.Local lub DateTimeKind.Unspecified, przesunięcie jest ustawione na wartość równą lokalnej strefie czasowej.

Analizowanie reprezentacji ciągu daty i godziny

DateTimeOffset Typ obsługuje cztery metody, które umożliwiają konwertowanie ciągu reprezentacji daty i godziny na DateTimeOffset wartość:

  • Parse, który próbuje przekonwertować reprezentację ciągu daty i godziny na DateTimeOffset wartość i zgłasza wyjątek, jeśli konwersja nie powiedzie się.

  • TryParse, który próbuje przekonwertować ciąg reprezentujący datę i godzinę na DateTimeOffset wartość i zwraca false wartość, jeśli konwersja nie powiedzie się.

  • ParseExact, który próbuje przekonwertować ciąg reprezentujący datę i godzinę w określonym formacie na DateTimeOffset wartość. Metoda zgłasza wyjątek, jeśli konwersja nie powiedzie się.

  • TryParseExact, który próbuje przekonwertować ciąg reprezentujący datę i godzinę w określonym formacie na DateTimeOffset wartość. Metoda zwraca false wartość , jeśli konwersja nie powiedzie się.

W poniższym przykładzie przedstawiono wywołania każdej z tych czterech metod konwersji ciągów w celu utworzenia DateTimeOffset wystąpienia wartości.

string timeString;
DateTimeOffset targetTime;

timeString = "05/01/2008 8:30 AM +01:00";
try
{
   targetTime = DateTimeOffset.Parse(timeString);
   Console.WriteLine(targetTime);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse {0}.", timeString);
}

timeString = "05/01/2008 8:30 AM";
if (DateTimeOffset.TryParse(timeString, out targetTime))
   Console.WriteLine(targetTime);
else
   Console.WriteLine("Unable to parse {0}.", timeString);

timeString = "Thursday, 01 May 2008 08:30";
try
{
   targetTime = DateTimeOffset.ParseExact(timeString, "f",
                CultureInfo.InvariantCulture);
   Console.WriteLine(targetTime);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse {0}.", timeString);
}

timeString = "Thursday, 01 May 2008 08:30 +02:00";
string formatString;
formatString = CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern +
                " " +
                CultureInfo.InvariantCulture.DateTimeFormat.ShortTimePattern +
                " zzz";
if (DateTimeOffset.TryParseExact(timeString,
                                formatString,
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.AllowLeadingWhite,
                                out targetTime))
   Console.WriteLine(targetTime);
else
   Console.WriteLine("Unable to parse {0}.", timeString);
// The example displays the following output to the console:
//    5/1/2008 8:30:00 AM +01:00
//    5/1/2008 8:30:00 AM -07:00
//    5/1/2008 8:30:00 AM -07:00
//    5/1/2008 8:30:00 AM +02:00
Dim timeString As String
Dim targetTime As DateTimeOffset

timeString = "05/01/2008 8:30 AM +01:00"
Try
    targetTime = DateTimeOffset.Parse(timeString)
    Console.WriteLine(targetTime)
Catch e As FormatException
    Console.WriteLine("Unable to parse {0}.", timeString)
End Try

timeString = "05/01/2008 8:30 AM"
If DateTimeOffset.TryParse(timeString, targetTime) Then
    Console.WriteLine(targetTime)
Else
    Console.WriteLine("Unable to parse {0}.", timeString)
End If

timeString = "Thursday, 01 May 2008 08:30"
Try
    targetTime = DateTimeOffset.ParseExact(timeString, "f", _
                 CultureInfo.InvariantCulture)
    Console.WriteLine(targetTime)
Catch e As FormatException
    Console.WriteLine("Unable to parse {0}.", timeString)
End Try

timeString = "Thursday, 01 May 2008 08:30 +02:00"
Dim formatString As String
formatString = CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern & _
                " " & _
                CultureInfo.InvariantCulture.DateTimeFormat.ShortTimePattern & _
                " zzz"
If DateTimeOffset.TryParseExact(timeString, _
                                formatString, _
                                CultureInfo.InvariantCulture, _
                                DateTimeStyles.AllowLeadingWhite, _
                                targetTime) Then
    Console.WriteLine(targetTime)
Else
    Console.WriteLine("Unable to parse {0}.", timeString)
End If
' The example displays the following output to the console:
'    5/1/2008 8:30:00 AM +01:00
'    5/1/2008 8:30:00 AM -07:00
'    5/1/2008 8:30:00 AM -07:00
'    5/1/2008 8:30:00 AM +02:00

Zobacz też