Bir DateTimeOffset nesnesinin örneğini oluşturma

Yapı, DateTimeOffset yeni DateTimeOffset değerler oluşturmak için çeşitli yollar sunar. Bunların çoğu, eşgüdümlü Evrensel Saat'ten (UTC) tarih ve saat değerinin uzaklığını belirtmenize olanak sağlayan geliştirmelerle yeni DateTime değerlerin örneğini oluşturma yöntemlerine doğrudan karşılık gelir. Özellikle, aşağıdaki yollarla bir DateTimeOffset değerin örneğini oluşturabilirsiniz:

  • Tarih ve saat değişmez değeri kullanarak.

  • Oluşturucuyu DateTimeOffset çağırarak.

  • Bir değeri örtük olarak değere DateTimeOffset dönüştürerek.

  • Bir tarih ve saatin dize gösterimini ayrıştırarak.

Bu konu başlığında, bu yeni DateTimeOffset değerlerin örneğini oluşturma yöntemlerini gösteren daha fazla ayrıntı ve kod örneği sağlanmaktadır.

Tarih ve saat değişmez değerleri

Bunu destekleyen diller için, bir DateTime değerin örneğini oluşturmanın en yaygın yollarından biri, tarih ve saati sabit kodlanmış değişmez değer olarak sağlamaktır. Örneğin, aşağıdaki Visual Basic kodu değeri 1 Mayıs 2008, 08:06:32 olan bir DateTime nesne oluşturur.

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

DateTimeOffset değerler, değişmez değerleri destekleyen DateTime diller kullanılırken tarih ve saat değişmez değerleri kullanılarak da başlatılabilir. Örneğin, aşağıdaki Visual Basic kodu bir DateTimeOffset nesne oluşturur.

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

Konsol çıkışında gösterildiği gibi, DateTimeOffset bu şekilde oluşturulan değere yerel saat diliminin uzaklığı atanır. Bu, karakter değişmez değeri kullanılarak atanan bir DateTimeOffset değerin, kod farklı bilgisayarlarda çalıştırılırsa tek bir zaman noktasını tanımlamadığı anlamına gelir.

DateTimeOffset oluşturucuları

türü DateTimeOffset altı oluşturucu tanımlar. Dört tanesi doğrudan oluşturuculara DateTime karşılık gelir ve utc'den tarih ve saat uzaklığını tanımlayan ek bir parametre türüne TimeSpan sahip olur. Bunlar, tek tek tarih ve saat bileşenlerinin değerine göre bir DateTimeOffset değer tanımlamanıza olanak sağlar. Örneğin, aşağıdaki kod, 1/5/2008 8:06:32 +01:00 aynı değerlere sahip nesnelerin örneğini DateTimeOffset oluşturmak için bu dört oluşturucuyu kullanır.

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

Nesnenin değeri, oluşturucusunun DateTimeOffset bağımsız değişkenlerinden biri olarak bir PersianCalendar nesne kullanılarak örneklendiğinde konsolda görüntülendiğinde, bu değerin Farsça takvim yerine Gregoryen'de bir tarih olarak ifade edildiğine dikkat edin. Farsça takvimi kullanarak bir tarihin çıktısını almak için konu başlığındaki PersianCalendar örne bakın.

Diğer iki oluşturucu bir değerden DateTime bir DateTimeOffset nesne oluşturur. Bunlardan ilki, DateTime bir değere dönüştürülecek değer olan tek bir DateTimeOffset parametreye sahiptir. Sonuçta DateTimeOffset elde edilen değerin uzaklığı, oluşturucunun Kind tek parametresinin özelliğine bağlıdır. Değeri ise DateTimeKind.Utc, uzaklık değerine eşit TimeSpan.Zeroolarak ayarlanır. Aksi takdirde, uzaklığı yerel saat dilimine eşit olarak ayarlanır. Aşağıdaki örnekte, UTC ve yerel saat dilimini temsil eden nesnelerin örneğini DateTimeOffset oluşturmak için bu oluşturucunun kullanımı gösterilmektedir:

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

'

Not

Tek DateTime bir parametreye sahip oluşturucunun DateTimeOffset aşırı yüklemesini çağırmak, bir değerin bir değere örtük bir şekilde dönüştürülmesiyle DateTimeDateTimeOffset eşdeğerdir.

Bir değerden DateTime nesne oluşturan DateTimeOffset ikinci oluşturucunun iki parametresi vardır: DateTime dönüştürülecek değer ve UTC'den tarih ve saatin uzaklığını temsil eden bir TimeSpan değer. Bu uzaklık değeri oluşturucunun Kind ilk parametresinin özelliğine karşılık gelir veya bir ArgumentException oluşturulur. İlk parametrenin Kind özelliği ise DateTimeKind.Utc, ikinci parametrenin değeri olmalıdır TimeSpan.Zero. İlk parametrenin Kind özelliği ise DateTimeKind.Local, ikinci parametrenin değeri yerel sistemin saat diliminin uzaklığı olmalıdır. İlk parametrenin Kind özelliği ise DateTimeKind.Unspecified, uzaklık herhangi bir geçerli değer olabilir. Aşağıdaki kod, değerlere dönüştürmek DateTimeDateTimeOffset için bu oluşturucuya yapılan çağrıları gösterir.

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

Örtük tür dönüştürme

Türü DateTimeOffset , bir örtük tür dönüştürmesini destekler: bir DateTime değerden değere DateTimeOffset . (Örtük tür dönüştürme, açık bir atama (C#'de) veya dönüştürme (Visual Basic'te) gerektirmeyen ve bilgileri kaybetmeyen bir türden diğerine dönüştürmedir.) Aşağıdaki gibi kodu mümkün kılar.

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

Elde DateTimeOffset edilen değerin uzaklığı özellik değerine bağlıdır DateTime.Kind . Değeri ise DateTimeKind.Utc, uzaklık değerine eşit TimeSpan.Zeroolarak ayarlanır. Değeri veya DateTimeKind.UnspecifiediseDateTimeKind.Local, uzaklık yerel saat diliminin değerine eşit olarak ayarlanır.

Tarih ve saatin dize gösterimini ayrıştırma

türü, DateTimeOffset bir tarih ve saatin dize gösterimini bir değere DateTimeOffset dönüştürmenize olanak sağlayan dört yöntemi destekler:

  • Parse, bir tarih ve saatin dize gösterimini bir DateTimeOffset değere dönüştürmeye çalışır ve dönüştürme başarısız olursa bir özel durum oluşturur.

  • TryParse, bir tarih ve saatin dize gösterimini bir DateTimeOffset değere dönüştürmeye çalışır ve dönüştürme başarısız olursa döndürür false .

  • ParseExact, belirtilen biçimdeki bir tarih ve saatin dize gösterimini bir DateTimeOffset değere dönüştürmeye çalışır. dönüştürme başarısız olursa yöntemi bir özel durum oluşturur.

  • TryParseExact, belirtilen biçimdeki bir tarih ve saatin dize gösterimini bir DateTimeOffset değere dönüştürmeye çalışır. Dönüştürme başarısız olursa yöntemi döndürür false .

Aşağıdaki örnek, bir DateTimeOffset değerin örneğini oluşturmak için bu dört dize dönüştürme yönteminin her birine yapılan çağrıları gösterir.

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

Ayrıca bkz.