DateTimeOffset Constructores

Definición

Inicializa una nueva instancia de la estructura DateTimeOffset.Initializes a new instance of the DateTimeOffset structure.

Sobrecargas

DateTimeOffset(DateTime)

Initializa una nueva instancia de la estructura DateTimeOffset mediante el valor DateTime especificado.Initializes a new instance of the DateTimeOffset structure using the specified DateTime value.

DateTimeOffset(DateTime, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el valor DateTime y el desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified DateTime value and offset.

DateTimeOffset(Int64, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el número de pasos y el desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified number of ticks and offset.

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el año, mes, día, hora, minuto, segundo y desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, and offset.

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset con los valores de año, mes, día, hora, minuto, segundo, milisegundo y desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset.

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando los valores de año, mes, día, hora, minuto, segundo, milisegundo y desplazamiento especificados de un calendario indicado.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset of a specified calendar.

DateTimeOffset(DateTime)

Initializa una nueva instancia de la estructura DateTimeOffset mediante el valor DateTime especificado.Initializes a new instance of the DateTimeOffset structure using the specified DateTime value.

public:
 DateTimeOffset(DateTime dateTime);
public DateTimeOffset (DateTime dateTime);
new DateTimeOffset : DateTime -> DateTimeOffset
Public Sub New (dateTime As DateTime)

Parámetros

dateTime
DateTime

Fecha y hora.A date and time.

Excepciones

La fecha y hora UTC (hora universal coordinada) que resulta de aplicar el desplazamiento es anterior a MinValue.The Coordinated Universal Time (UTC) date and time that results from applying the offset is earlier than MinValue.

o bien-or- La fecha y hora UTC que resulta de aplicar el desplazamiento es posterior a MaxValue.The UTC date and time that results from applying the offset is later than MaxValue.

Ejemplos

En el ejemplo siguiente se muestra cómo el valor de la DateTime.Kind propiedad del dateTime parámetro afecta al valor de fecha y hora devuelto por este constructor.The following example illustrates how the value of the DateTime.Kind property of the dateTime parameter affects the date and time value that is returned by this constructor.

DateTime localNow = DateTime.Now;
DateTimeOffset localOffset = new DateTimeOffset(localNow);
Console.WriteLine(localOffset.ToString());

DateTime utcNow = DateTime.UtcNow;
DateTimeOffset utcOffset = new DateTimeOffset(utcNow);
Console.WriteLine(utcOffset.ToString());

DateTime unspecifiedNow = DateTime.SpecifyKind(DateTime.Now,
                               DateTimeKind.Unspecified);
DateTimeOffset unspecifiedOffset = new DateTimeOffset(unspecifiedNow);
Console.WriteLine(unspecifiedOffset.ToString());
//
// The code produces the following output if run on Feb. 23, 2007, on
// a system 8 hours earlier than UTC:
//   2/23/2007 4:21:58 PM -08:00
//   2/24/2007 12:21:58 AM +00:00
//   2/23/2007 4:21:58 PM -08:00
Dim localNow As Date = Date.Now
Dim localOffset As New DateTimeOffset(localNow)
Console.WriteLine(localOffset.ToString())

Dim utcNow As Date = Date.UtcNow
Dim utcOffset As New DateTimeOffset(utcNow)
Console.WriteLine(utcOffset.ToString())

Dim unspecifiedNow As Date = Date.SpecifyKind(Date.Now, _
                                  DateTimeKind.Unspecified)
Dim unspecifiedOffset As New DateTimeOffset(unspecifiedNow)
Console.WriteLine(unspecifiedOffset.ToString())
'
' The code produces the following output if run on Feb. 23, 2007, on
' a system 8 hours earlier than UTC:
'    2/23/2007 4:21:58 PM -08:00
'    2/24/2007 12:21:58 AM +00:00
'    2/23/2007 4:21:58 PM -08:00      

Comentarios

El comportamiento de este constructor depende del valor de la DateTime.Kind propiedad del dateTime parámetro:This constructor's behavior depends on the value of the DateTime.Kind property of the dateTime parameter:

Se aplica a

DateTimeOffset(DateTime, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el valor DateTime y el desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified DateTime value and offset.

public:
 DateTimeOffset(DateTime dateTime, TimeSpan offset);
public DateTimeOffset (DateTime dateTime, TimeSpan offset);
new DateTimeOffset : DateTime * TimeSpan -> DateTimeOffset
Public Sub New (dateTime As DateTime, offset As TimeSpan)

Parámetros

dateTime
DateTime

Fecha y hora.A date and time.

offset
TimeSpan

Desplazamiento de hora a partir de la hora universal coordinada (UTC).The time's offset from Coordinated Universal Time (UTC).

Excepciones

dateTime.Kind es igual a Utc y offset no es igual a cero.dateTime.Kind equals Utc and offset does not equal zero.

o bien-or- dateTime.Kind es igual a Local y offset no es igual al desplazamiento de zona horaria local del sistema.dateTime.Kind equals Local and offset does not equal the offset of the system's local time zone.

o bien-or- offset no está especificado en minutos enteros.offset is not specified in whole minutes.

offset es menor que -14 horas o mayor que 14 horas.offset is less than -14 hours or greater than 14 hours.

o bien-or- UtcDateTime es menor que MinValue o mayor que MaxValue.UtcDateTime is less than MinValue or greater than MaxValue.

Ejemplos

En el ejemplo siguiente se muestra cómo inicializar un DateTimeOffset objeto con una fecha y hora y el desplazamiento de la zona horaria local cuando esa zona horaria no se conoce de antemano.The following example shows how to initialize a DateTimeOffset object with a date and time and the offset of the local time zone when that time zone is not known in advance.

DateTime localTime = new DateTime(2007, 07, 12, 06, 32, 00);
DateTimeOffset dateAndOffset = new DateTimeOffset(localTime,
                         TimeZoneInfo.Local.GetUtcOffset(localTime));
Console.WriteLine(dateAndOffset);
// The code produces the following output:
//    7/12/2007 6:32:00 AM -07:00
Dim localTime As Date = #07/12/2007 6:32AM#
Dim dateAndOffset As New DateTimeOffset(localTime, _
                         TimeZoneInfo.Local.GetUtcOffset(localTime))
Console.WriteLine(dateAndOffset)
' The code produces the following output:
'    7/12/2007 6:32:00 AM -07:00

Comentarios

El comportamiento de este constructor depende en parte del valor de la Kind propiedad del dateTime parámetro:This constructor's behavior depends in part on the value of the Kind property of the dateTime parameter:

Se aplica a

DateTimeOffset(Int64, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el número de pasos y el desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified number of ticks and offset.

public:
 DateTimeOffset(long ticks, TimeSpan offset);
public DateTimeOffset (long ticks, TimeSpan offset);
new DateTimeOffset : int64 * TimeSpan -> DateTimeOffset
Public Sub New (ticks As Long, offset As TimeSpan)

Parámetros

ticks
Int64

Fecha y hora expresadas como el número de intervalos de 100 nanosegundos transcurridos desde la medianoche (00:00:00) del 1 de enero de 0001.A date and time expressed as the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight on January 1, 0001.

offset
TimeSpan

Desplazamiento de hora a partir de la hora universal coordinada (UTC).The time's offset from Coordinated Universal Time (UTC).

Excepciones

offset no está especificado en minutos enteros.offset is not specified in whole minutes.

La propiedad UtcDateTime es anterior a MinValue o posterior a MaxValue.The UtcDateTime property is earlier than MinValue or later than MaxValue.

o bien-or- ticks es menor que DateTimeOffset.MinValue.Ticks o mayor que DateTimeOffset.MaxValue.Ticks.ticks is less than DateTimeOffset.MinValue.Ticks or greater than DateTimeOffset.MaxValue.Ticks.

o bien-or- Offset es menor que -14 horas o mayor que 14 horas.Offset s less than -14 hours or greater than 14 hours.

Ejemplos

En el ejemplo siguiente se inicializa un DateTimeOffset objeto usando el número de TICs en una fecha arbitraria (en este caso, el 16 de julio de 2007, a las 1:32 PM) con un desplazamiento de-5.The following example initializes a DateTimeOffset object by using the number of ticks in an arbitrary date (in this case, July 16, 2007, at 1:32 PM) with an offset of -5.

DateTime dateWithoutOffset = new DateTime(2007, 7, 16, 13, 32, 00);
DateTimeOffset timeFromTicks = new DateTimeOffset(dateWithoutOffset.Ticks,
                               new TimeSpan(-5, 0, 0));
Console.WriteLine(timeFromTicks.ToString());
// The code produces the following output:
//    7/16/2007 1:32:00 PM -05:00
Dim dateWithoutOffset As Date = #07/16/2007 1:32PM#
Dim timeFromTicks As New DateTimeOffset(datewithoutOffset.Ticks, _
                         New TimeSpan(-5, 0, 0))
Console.WriteLine(timeFromTicks.ToString())
' The code produces the following output:
'    7/16/2007 1:32:00 PM -05:00

Comentarios

Normalmente, si se intenta llamar al DateTimeOffset constructor para crear una instancia DateTimeOffset de un valor con una hora local y un desplazamiento distinto del de la zona horaria local, se produce una excepción ArgumentException .Ordinarily, trying to call the DateTimeOffset constructor to instantiate a DateTimeOffset value with a local time and an offset other than that of the local time zone throws an ArgumentException. Puede usar esta sobrecarga del DateTimeOffset constructor para solucionar esta limitación.You can use this overload of the DateTimeOffset constructor to work around this limitation. En el ejemplo siguiente se usa el número de pasos de la hora local para crear una instancia de un DateTimeOffset valor cuyo desplazamiento no representa necesariamente el de la hora local:The following example uses the local time's number of ticks to instantiate a DateTimeOffset value whose offset does not necessarily represent that of the local time:

DateTime localTime = DateTime.Now;
DateTimeOffset nonLocalDateWithOffset = new DateTimeOffset(localTime.Ticks,
                                  new TimeSpan(2, 0, 0));
Console.WriteLine(nonLocalDateWithOffset);
//
// The code produces the following output if run on Feb. 23, 2007:
//    2/23/2007 4:37:50 PM +02:00
Dim localTime As Date = Date.Now
Dim nonLocalDateWithOffset As New DateTimeOffset(localTime.Ticks, _
                                  New TimeSpan(2, 0, 0))
Console.WriteLine(nonLocalDateWithOffset)                                        
'
' The code produces the following output if run on Feb. 23, 2007:
'    2/23/2007 4:37:50 PM +02:00

Se aplica a

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando el año, mes, día, hora, minuto, segundo y desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, and offset.

public:
 DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset);
public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, TimeSpan offset);
new DateTimeOffset : int * int * int * int * int * int * TimeSpan -> DateTimeOffset
Public Sub New (year As Integer, month As Integer, day As Integer, hour As Integer, minute As Integer, second As Integer, offset As TimeSpan)

Parámetros

year
Int32

Año (del 1 al 9999).The year (1 through 9999).

month
Int32

Mes (del 1 al 12).The month (1 through 12).

day
Int32

Día (del 1 al número de días de month).The day (1 through the number of days in month).

hour
Int32

Horas (de 0 a 23).The hours (0 through 23).

minute
Int32

Minutos (de 0 a 59).The minutes (0 through 59).

second
Int32

Segundos (de 0 a 59).The seconds (0 through 59).

offset
TimeSpan

Desplazamiento de hora a partir de la hora universal coordinada (UTC).The time's offset from Coordinated Universal Time (UTC).

Excepciones

offset no representa los minutos enteros.offset does not represent whole minutes.

year es menor que uno o mayor que 9999.year is less than one or greater than 9999.

o bien-or- month es menor que uno o mayor que 12.month is less than one or greater than 12.

o bien-or- day es menor que 1 o mayor que el número de días de month.day is less than one or greater than the number of days in month.

o bien-or- hour es menor que cero o mayor que 23.hour is less than zero or greater than 23.

o bien-or- minute es menor que 0 o mayor que 59.minute is less than 0 or greater than 59.

O bien-or- second es menor que 0 o mayor que 59.second is less than 0 or greater than 59.

o bien-or- offset es menor que -14 horas o mayor que 14 horas.offset is less than -14 hours or greater than 14 hours.

o bien-or- La propiedad UtcDateTime es anterior a MinValue o posterior a MaxValue.The UtcDateTime property is earlier than MinValue or later than MaxValue.

Ejemplos

En el ejemplo siguiente se crea una instancia de un DateTimeOffset objeto utilizando la DateTimeOffset.DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) sobrecarga del constructor.The following example instantiates a DateTimeOffset object by using the DateTimeOffset.DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) constructor overload.

   DateTime specificDate = new DateTime(2008, 5, 1, 06, 32, 00);
   DateTimeOffset offsetDate = new DateTimeOffset(specificDate.Year,
                                   specificDate.Month,
                                   specificDate.Day,
                                   specificDate.Hour,
                                   specificDate.Minute,
                                   specificDate.Second,
                                   new TimeSpan(-5, 0, 0));
   Console.WriteLine("Current time: {0}", offsetDate);
   Console.WriteLine("Corresponding UTC time: {0}", offsetDate.UtcDateTime);
// The code produces the following output:
//    Current time: 5/1/2008 6:32:00 AM -05:00
//    Corresponding UTC time: 5/1/2008 11:32:00 AM
   Dim specificDate As Date = #5/1/2008 6:32AM#
   Dim offsetDate As New DateTimeOffset(specificDate.Year, _
                                        specificDate.Month, _
                                        specificDate.Day, _
                                        specificDate.Hour, _
                                        specificDate.Minute, _
                                        specificDate.Second, _
                                        New TimeSpan(-5, 0, 0))
   Console.WriteLine("Current time: {0}", offsetDate)
   Console.WriteLine("Corresponding UTC time: {0}", offsetDate.UtcDateTime)                                              
' The code produces the following output:
'    Current time: 5/1/2008 6:32:00 AM -05:00
'    Corresponding UTC time: 5/1/2008 11:32:00 AM      

Comentarios

Este constructor interpreta year , month y day como un año, mes y día en el calendario gregoriano.This constructor interprets year, month, and day as a year, month, and day in the Gregorian calendar. Para crear una instancia de un DateTimeOffset valor usando el año, el mes y el día de otro calendario, llame al DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) constructor.To instantiate a DateTimeOffset value by using the year, month, and day in another calendar, call the DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) constructor.

Se aplica a

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset con los valores de año, mes, día, hora, minuto, segundo, milisegundo y desplazamiento especificados.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset.

public:
 DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset);
public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset);
new DateTimeOffset : int * int * int * int * int * int * int * TimeSpan -> DateTimeOffset
Public Sub New (year As Integer, month As Integer, day As Integer, hour As Integer, minute As Integer, second As Integer, millisecond As Integer, offset As TimeSpan)

Parámetros

year
Int32

Año (del 1 al 9999).The year (1 through 9999).

month
Int32

Mes (del 1 al 12).The month (1 through 12).

day
Int32

Día (del 1 al número de días de month).The day (1 through the number of days in month).

hour
Int32

Horas (de 0 a 23).The hours (0 through 23).

minute
Int32

Minutos (de 0 a 59).The minutes (0 through 59).

second
Int32

Segundos (de 0 a 59).The seconds (0 through 59).

millisecond
Int32

Milisegundos (de 0 a 999).The milliseconds (0 through 999).

offset
TimeSpan

Desplazamiento de hora a partir de la hora universal coordinada (UTC).The time's offset from Coordinated Universal Time (UTC).

Excepciones

offset no representa los minutos enteros.offset does not represent whole minutes.

year es menor que uno o mayor que 9999.year is less than one or greater than 9999.

o bien-or- month es menor que uno o mayor que 12.month is less than one or greater than 12.

o bien-or- day es menor que 1 o mayor que el número de días de month.day is less than one or greater than the number of days in month.

o bien-or- hour es menor que cero o mayor que 23.hour is less than zero or greater than 23.

o bien-or- minute es menor que 0 o mayor que 59.minute is less than 0 or greater than 59.

O bien-or- second es menor que 0 o mayor que 59.second is less than 0 or greater than 59.

O bien-or- millisecond es menor que 0 o mayor que 999.millisecond is less than 0 or greater than 999.

o bien-or- offset es menor que -14 o mayor que 14.offset is less than -14 or greater than 14.

o bien-or- La propiedad UtcDateTime es anterior a MinValue o posterior a MaxValue.The UtcDateTime property is earlier than MinValue or later than MaxValue.

Ejemplos

En el ejemplo siguiente se crea una instancia de un DateTimeOffset objeto utilizando la DateTimeOffset.DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) sobrecarga del constructor.The following example instantiates a DateTimeOffset object by using the DateTimeOffset.DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) constructor overload.

string fmt = "dd MMM yyyy HH:mm:ss";
DateTime thisDate = new DateTime(2007, 06, 12, 19, 00, 14, 16);
DateTimeOffset offsetDate = new DateTimeOffset(thisDate.Year,
                                               thisDate.Month,
                                               thisDate.Day,
                                               thisDate.Hour,
                                               thisDate.Minute,
                                               thisDate.Second,
                                               thisDate.Millisecond,
                                               new TimeSpan(2, 0, 0));
Console.WriteLine("Current time: {0}:{1}", offsetDate.ToString(fmt), offsetDate.Millisecond);
// The code produces the following output:
//    Current time: 12 Jun 2007 19:00:14:16
Dim fmt As String = "dd MMM yyyy HH:mm:ss"
Dim thisDate As DateTime = New Date(2007, 06, 12, 19, 00, 14, 16)
Dim offsetDate As New DateTimeOffset(thisDate.Year, _
                                     thisDate.Month, _
                                     thisDate.Day, _
                                     thisDate.Hour, _
                                     thisDate.Minute, _
                                     thisDate.Second, _
                                     thisDate.Millisecond, _ 
                                     New TimeSpan(2, 0, 0))  
Console.WriteLine("Current time: {0}:{1}", offsetDate.ToString(fmt), _ 
                                           offsetDate.Millisecond)
' The code produces the following output:
'    Current time: 12 Jun 2007 19:00:14:16      

Comentarios

Este constructor interpreta year , month y day como un año, mes y día en el calendario gregoriano.This constructor interprets year, month, and day as a year, month, and day in the Gregorian calendar. Para crear una instancia de un DateTimeOffset valor usando el año, el mes y el día de otro calendario, llame al DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) constructor.To instantiate a DateTimeOffset value by using the year, month, and day in another calendar, call the DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) constructor.

Se aplica a

DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan)

Inicializa una nueva instancia de la estructura DateTimeOffset usando los valores de año, mes, día, hora, minuto, segundo, milisegundo y desplazamiento especificados de un calendario indicado.Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset of a specified calendar.

public:
 DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, System::Globalization::Calendar ^ calendar, TimeSpan offset);
public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar, TimeSpan offset);
new DateTimeOffset : int * int * int * int * int * int * int * System.Globalization.Calendar * TimeSpan -> DateTimeOffset
Public Sub New (year As Integer, month As Integer, day As Integer, hour As Integer, minute As Integer, second As Integer, millisecond As Integer, calendar As Calendar, offset As TimeSpan)

Parámetros

year
Int32

Año.The year.

month
Int32

Mes (del 1 al 12).The month (1 through 12).

day
Int32

Día (del 1 al número de días de month).The day (1 through the number of days in month).

hour
Int32

Horas (de 0 a 23).The hours (0 through 23).

minute
Int32

Minutos (de 0 a 59).The minutes (0 through 59).

second
Int32

Segundos (de 0 a 59).The seconds (0 through 59).

millisecond
Int32

Milisegundos (de 0 a 999).The milliseconds (0 through 999).

calendar
Calendar

Calendario que se usa para interpretar year, month y day.The calendar that is used to interpret year, month, and day.

offset
TimeSpan

Desplazamiento de hora a partir de la hora universal coordinada (UTC).The time's offset from Coordinated Universal Time (UTC).

Excepciones

offset no representa los minutos enteros.offset does not represent whole minutes.

El valor de calendar no puede ser null.calendar cannot be null.

year es menor que MinSupportedDateTime.Year del parámetro calendar o mayor que MaxSupportedDateTime.Year.year is less than the calendar parameter's MinSupportedDateTime.Year or greater than MaxSupportedDateTime.Year.

o bien-or- month es menor o mayor que el número de meses de year en el calendar.month is either less than or greater than the number of months in year in the calendar.

o bien-or- day es menor que 1 o mayor que el número de días de month.day is less than one or greater than the number of days in month.

o bien-or- hour es menor que cero o mayor que 23.hour is less than zero or greater than 23.

o bien-or- minute es menor que 0 o mayor que 59.minute is less than 0 or greater than 59.

O bien-or- second es menor que 0 o mayor que 59.second is less than 0 or greater than 59.

O bien-or- millisecond es menor que 0 o mayor que 999.millisecond is less than 0 or greater than 999.

o bien-or- offset es menor que -14 horas o mayor que 14 horas.offset is less than -14 hours or greater than 14 hours.

o bien-or- Los parámetros year, month y day no se pueden representar como un valor de fecha y hora.The year, month, and day parameters cannot be represented as a date and time value.

o bien-or- La propiedad UtcDateTime es anterior a MinValue o posterior a MaxValue.The UtcDateTime property is earlier than MinValue or later than MaxValue.

Ejemplos

En el ejemplo siguiente se usan instancias de la HebrewCalendar clase y de la HijriCalendar clase para crear una instancia de un DateTimeOffset valor.The following example uses instances of both the HebrewCalendar class and the HijriCalendar class to instantiate a DateTimeOffset value. Esta fecha se muestra a continuación en la consola mediante los calendarios respectivos y el calendario gregoriano.That date is then displayed to the console using the respective calendars and the Gregorian calendar.

CultureInfo fmt;
int year;
Calendar cal;
DateTimeOffset dateInCal;

// Instantiate DateTimeOffset with Hebrew calendar
year = 5770;
cal = new HebrewCalendar();
fmt = new CultureInfo("he-IL");
fmt.DateTimeFormat.Calendar = cal;
dateInCal = new DateTimeOffset(year, 7, 12,
                               15, 30, 0, 0,
                               cal,
                               new TimeSpan(2, 0, 0));
// Display the date in the Hebrew calendar
Console.WriteLine("Date in Hebrew Calendar: {0:g}",
                   dateInCal.ToString(fmt));
// Display the date in the Gregorian calendar
Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal);
Console.WriteLine();

// Instantiate DateTimeOffset with Hijri calendar
year = 1431;
cal = new HijriCalendar();
fmt = new CultureInfo("ar-SA");
fmt.DateTimeFormat.Calendar = cal;
dateInCal = new DateTimeOffset(year, 7, 12,
                               15, 30, 0, 0,
                               cal,
                               new TimeSpan(2, 0, 0));
// Display the date in the Hijri calendar
Console.WriteLine("Date in Hijri Calendar: {0:g}",
                   dateInCal.ToString(fmt));
// Display the date in the Gregorian calendar
Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal);
Console.WriteLine();
Dim fmt As CultureInfo
Dim year As Integer
Dim cal As Calendar
Dim dateInCal As DateTimeOffset

' Instantiate DateTimeOffset with Hebrew calendar
year = 5770
cal = New HebrewCalendar()
fmt = New CultureInfo("he-IL")
fmt.DateTimeFormat.Calendar = cal      
dateInCal = New DateTimeOffset(year, 7, 12, _
                               15, 30, 0, 0, _
                               cal, _
                               New TimeSpan(2, 0, 0))
' Display the date in the Hebrew calendar
Console.WriteLine("Date in Hebrew Calendar: {0:g}", _
                   dateInCal.ToString(fmt))
' Display the date in the Gregorian calendar                         
Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal)
Console.WriteLine()

' Instantiate DateTimeOffset with Hijri calendar
year = 1431
cal = New HijriCalendar()
fmt = New CultureInfo("ar-SA")
fmt.DateTimeFormat.Calendar = cal
dateInCal = New DateTimeOffset(year, 7, 12, _
                               15, 30, 0, 0, _
                               cal, _
                               New TimeSpan(2, 0, 0))
' Display the date in the Hijri calendar
Console.WriteLine("Date in Hijri Calendar: {0:g}", _
                   dateInCal.ToString(fmt))
' Display the date in the Gregorian calendar                         
Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal)
Console.WriteLine()

Comentarios

Los year month parámetros,, day , hour , minute , second y millisecond reflejan todos los valores expresados en el calendario especificado por el calendar parámetro.The year, month, day, hour, minute, second, and millisecond parameters all reflect values expressed in the calendar specified by the calendar parameter. Se produce una excepción si estos valores forman una fecha y hora que no se pueden expresar mediante este calendario.An exception is thrown if these values form a date and time that cannot be expressed by using this calendar.

Importante

Las eras en los calendarios japoneses se basan en el reino del emperador y, por tanto, se espera que cambien.Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. Por ejemplo, el 1 de mayo de 2019 marcaba el comienzo de la era Reiwa en JapaneseCalendar y JapaneseLunisolarCalendar.For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. Este cambio de era afecta a todas las aplicaciones que usan estos calendarios.Such a change of era affects all applications that use these calendars. Para obtener más información y determinar si sus aplicaciones están entre las afectadas, consulte Handling a new era in the Japanese calendar in .NET (Gestión de una nueva era del calendario japonés en .NET).See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. Para obtener más información sobre cómo probar aplicaciones en sistemas Windows para garantizar que estén preparadas para el cambio de era, consulte Prepare your application for the Japanese era change (Preparación de la aplicación para el cambio de era japonesa).See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. Consulte Trabajar con eras para ver las características de .NET que admiten calendarios con varias eras y procedimientos recomendados al trabajar con calendarios que admiten varias eras.See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

Se aplica a