Aracılığıyla paylaş


DateTimeOffset nesnesinin örneğini oluşturma

DateTimeOffset yapısı, yeni DateTimeOffset değerleri oluşturmak için çeşitli yollar sunar. Bunların çoğu, Eşgüdümlü Evrensel Zaman (UTC) baz alınarak tarih ve saat değerinin uzaklığını belirtmenize olanak tanıyan geliştirmelerle, yeni DateTime öğelerinin oluşturulması için mevcut yöntemlere doğrudan karşılık gelir. Özellikle, aşağıdaki yollarla bir DateTimeOffset değeri örneği oluşturabilirsiniz:

  • Tarih ve saat sabiti kullanarak.

  • Bir DateTimeOffset oluşturucuyu çağırarak.

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

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

Bu konu, yeni DateTimeOffset değerlerini oluşturma yöntemlerini daha ayrıntılı biçimde sunar ve bunları gösteren kod örneklerini içerir.

Tarih ve saat sabitleri

Bu özelliği destekleyen dillerde, bir DateTime değerini oluşturmanın en yaygın yolu, tarih ve saati sabit kodlanmış bir 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 nesnesi 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ğerleri, DateTime değişmez değerlerini destekleyen dillerde, tarih ve saat değişmez değerleri kullanılarak da başlatılabilir. Örneğin, aşağıdaki Visual Basic kodu bir DateTimeOffset nesnesi 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, bu şekilde oluşturulan DateTimeOffset değerine yerel saat diliminin uzaklığı atanır. Bu, karakter değişmez değeri kullanılarak atanan bir DateTimeOffset değerinin, kod farklı bilgisayarlarda çalıştırılırsa tek bir zaman noktasını tanımlamadığı anlamına gelir.

DateTimeOffset oluşturucuları

DateTimeOffset türü altı oluşturucuyu tanımlar. Dört tanesi doğrudan DateTime oluşturuculara karşılık gelir ve utc'ye göre tarih ve saatin uzaklığını tanımlayan TimeSpan türünde ek bir parametreye sahip olur. Bunlar, tek tek tarih ve saat bileşenlerinin değerine göre DateTimeOffset bir 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 DateTimeOffset nesneleri 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($"{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($"{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

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

Diğer iki oluşturucu, bir DateTimeOffset değerinden DateTime nesnesi oluşturur. Bunlardan ilki, DateTime değerini DateTimeOffset değerine dönüştüren tek bir parametreye sahiptir. Sonuçta elde edilen DateTimeOffset değerin uzaklığı, oluşturucunun tek parametresinin Kind özelliğine bağlıdır. Değeri DateTimeKind.Utcise, uzaklık TimeSpan.Zerodeğerine eşit olarak ayarlanır. Aksi takdirde, uzaklığı yerel saat dilimine eşit olarak ayarlanır. Aşağıdaki örnekte, UTC ve yerel saat dilimini temsil eden DateTimeOffset nesnelerinin örneğini 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 {targetTime} failed.");
}
// 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.

'

Uyarı

Tek bir DateTimeOffset parametresine sahip DateTime oluşturucusunun aşırı yüklenmesini çağırmak, DateTime değerin DateTimeOffset bir değere örtük olarak dönüştürülmesiyle eşdeğerdir.

bir DateTimeOffset değerinden DateTime nesnesi oluşturan ikinci oluşturucunun iki parametresi vardır: dönüştürülecek DateTime değeri ve UTC'den tarih ve saatin uzaklığını temsil eden bir TimeSpan değeri. Bu uzaklık değeri, oluşturucunun ilk parametresinin Kind özelliğine karşılık gelmelidir, aksi takdirde bir ArgumentException fırlatılır. İlk parametrenin Kind özelliği DateTimeKind.Utcise, ikinci parametrenin değeri TimeSpan.Zeroolmalıdır. İlk parametrenin Kind özelliği DateTimeKind.Localise, ikinci parametrenin değeri yerel sistemin saat diliminin uzaklığı olmalıdır. İlk parametrenin Kind özelliği DateTimeKind.Unspecifiedise, ofset geçerli herhangi bir değer olabilir. Aşağıdaki kod, DateTimeDateTimeOffset değerlere dönüştürmek 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 {utcTime} failed.");
}
// 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 {localTime} failed.");
}
// 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

Gizli tür dönüştürme

DateTimeOffset türü, bir örtük tür dönüştürmeyi destekler: DateTime değerinden DateTimeOffset değerine. (Örtük tür dönüşümü, C#'de açık bir atama veya Visual Basic'te bir dönüşüm gerektirmeyen ve bilgi kaybı yaşatmayan bir türden diğerine dönüşümdür.) 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 edilen DateTimeOffset değerinin uzaklığı DateTime.Kind özellik değerine bağlıdır. Değeri DateTimeKind.Utcise, uzaklık TimeSpan.Zerodeğerine eşit olarak ayarlanır. Değeri DateTimeKind.Local veya DateTimeKind.Unspecifiedise, uzaklık yerel saat dilimine eşit olarak ayarlanır.

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

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

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

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

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

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

Aşağıdaki örnek, bir DateTimeOffset değeri örneği 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 {timeString}.");
}

timeString = "05/01/2008 8:30 AM";
if (DateTimeOffset.TryParse(timeString, out targetTime))
   Console.WriteLine(targetTime);
else
   Console.WriteLine($"Unable to parse {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 {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 {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.