DateTimeOffset構造体には、新しいDateTimeOffset値を作成するさまざまな方法が用意されています。 その多くは、新しい DateTime 値のインスタンス化に使用できるメソッドに直接対応しています。この機能強化により、世界協定時刻 (UTC) からの日付と時刻の値のオフセットを指定できます。 具体的には、次の方法で DateTimeOffset 値をインスタンス化できます。
日付と時刻のリテラルを使用する。
DateTimeOffset コンストラクターを呼び出すこと。
値を暗黙的に DateTimeOffset 値に変換する。
日付と時刻の文字列形式を解析する。
このトピックでは、新しい DateTimeOffset 値をインスタンス化するこれらのメソッドを示す、より詳細なコード例を示します。
日付および時刻のリテラル
これをサポートする言語の場合、 DateTime 値をインスタンス化する最も一般的な方法の 1 つは、ハードコーディングされたリテラル値として日時を指定することです。 たとえば、次の Visual Basic コードでは、値が 2008 年 5 月 1 日午前 8 時 6 分 32 分の DateTime オブジェクトが作成されます。
Dim literalDate1 As Date = #05/01/2008 8:06:32 AM#
Console.WriteLine(literalDate1.ToString())
' Displays:
' 5/1/2008 8:06:32 AM
DateTimeOffset DateTimeリテラルをサポートする言語を使用する場合は、日付と時刻のリテラルを使用して値を初期化することもできます。 たとえば、次の Visual Basic コードでは、 DateTimeOffset オブジェクトが作成されます。
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
コンソールの出力が示すように、この方法で作成された DateTimeOffset 値には、ローカル タイム ゾーンのオフセットが割り当てられます。 つまり、コードが別のコンピューターで実行されている場合、文字リテラルを使用して割り当てられた DateTimeOffset 値は単一の時点を識別しません。
DateTimeOffset コンストラクター
DateTimeOffset型は、6 つのコンストラクターを定義します。 そのうちの 4 つ DateTime コンストラクターに直接対応し、UTC からの日付と時刻のオフセットを定義する TimeSpan 型の追加パラメーターを指定します。 これにより、個々の日時コンポーネントの値に基づいて DateTimeOffset 値を定義できます。 たとえば、次のコードでは、これら 4 つのコンストラクターを使用して、2008 年 5 月 1 日 8:06:32 +01:00 と同じ値を持つ DateTimeOffset オブジェクトをインスタンス化します。
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
DateTimeOffset オブジェクトを使用してインスタンス化されたPersianCalendar オブジェクトの値がコンストラクターの引数の 1 つとしてコンソールに表示される場合は、ペルシャ暦ではなくグレゴリオ暦の日付として表されることに注意してください。 ペルシア暦を使用して日付を出力するには、 PersianCalendar トピックの例を参照してください。
他の 2 つのコンストラクターは、DateTimeOffset値からDateTime オブジェクトを作成します。 これらの最初のパラメーターには、DateTime値に変換するDateTimeOffset値が 1 つ含まれます。 結果の DateTimeOffset 値のオフセットは、コンストラクターの単一パラメーターの Kind プロパティによって異なります。 値が DateTimeKind.Utcの場合、オフセットは TimeSpan.Zeroに等しく設定されます。 それ以外の場合、そのオフセットはローカル タイム ゾーンのオフセットと同じに設定されます。 次の例は、このコンストラクターを使用して、UTC とローカル タイム ゾーンを表す DateTimeOffset オブジェクトをインスタンス化する方法を示しています。
// 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.
'
注
単一のDateTimeOffset パラメーターを持つDateTime コンストラクターのオーバーロードを呼び出すことは、DateTime値からDateTimeOffset値への暗黙的な変換を実行することと同じです。
DateTimeOffset値からDateTime オブジェクトを作成する 2 番目のコンストラクターには、変換するDateTime値と、UTC からの日付と時刻のオフセットを表すTimeSpan値の 2 つのパラメーターがあります。 このオフセット値は、コンストラクターの最初のパラメーターの Kind プロパティに対応している必要があります。そうでない場合、ArgumentException がスローされます。 最初のパラメーターの Kind プロパティが DateTimeKind.Utc場合、2 番目のパラメーターの値は TimeSpan.Zeroする必要があります。 最初のパラメーターの Kind プロパティが DateTimeKind.Local場合、2 番目のパラメーターの値はローカル システムのタイム ゾーンのオフセットである必要があります。 最初のパラメーターの Kind プロパティが DateTimeKind.Unspecified場合、オフセットには任意の有効な値を指定できます。 次のコードは、このコンストラクターを呼び出して、 DateTime を DateTimeOffset 値に変換する方法を示しています。
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
暗黙的な型変換
DateTimeOffset型では、値からDateTime値への 1 つのDateTimeOffset型変換がサポートされています。 (暗黙的な型変換とは、明示的なキャスト (C#) や変換 (Visual Basic の場合) を必要とせず、情報を失わない型から別の型への変換です)。 これにより、次のようなコードが可能になります。
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
結果の DateTimeOffset 値のオフセットは、 DateTime.Kind プロパティ値によって異なります。 値が DateTimeKind.Utcの場合、オフセットは TimeSpan.Zeroに等しく設定されます。 値が DateTimeKind.Local または DateTimeKind.Unspecifiedの場合、オフセットはローカル タイム ゾーンのオフセットと同じに設定されます。
日付と時刻の文字列形式の解析
DateTimeOffset型では、日付と時刻の文字列形式をDateTimeOffset値に変換できる 4 つのメソッドがサポートされています。
Parseは、日付と時刻の文字列形式を DateTimeOffset 値に変換しようと試み、変換が失敗した場合に例外をスローします。
TryParseは、日付と時刻の文字列形式を DateTimeOffset 値に変換しようと試み、変換が失敗した場合に
falseを返します。ParseExactは、指定した形式の日付と時刻の文字列形式を DateTimeOffset 値に変換しようとします。 変換が失敗した場合、メソッドは例外をスローします。
TryParseExactは、指定した形式の日付と時刻の文字列形式を DateTimeOffset 値に変換しようとします。 このメソッドは、変換が失敗した場合に
falseを返します。
次の例は、これら 4 つの文字列変換メソッドのそれぞれを呼び出して、 DateTimeOffset 値をインスタンス化する方法を示しています。
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
こちらも参照ください
.NET