Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

DateTime-Struktur

 

Stellt einen Zeitpunkt dar, der normalerweise durch Datum und Uhrzeit dargestellt wird.

Informationen zum Durchsuchen des .NET Framework-Quellcodes für diesen Typ finden Sie in der Verweisquelle.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, IConvertible, 
	ISerializable, IComparable<DateTime>, IEquatable<DateTime>

NameBeschreibung
System_CAPS_pubmethodDateTime(Int32, Int32, Int32)

Initialisiert eine neue Instanz der DateTime-Struktur mit dem angegebenen Jahr, Monat und Tag.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Calendar)

Initialisiert eine neue Instanz der DateTime-Struktur mit dem angegebenen Jahr, Monat und Tag für den angegebenen Kalender.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute und Sekunde.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute und Sekunde für den angegebenen Kalender.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute, Sekunde und koordinierte Weltzeit (Coordinated Universal Time, UTC) oder Ortszeit.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute, Sekunde und Millisekunde.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute, Sekunde und Millisekunde für den angegebenen Kalender.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute, Sekunde, Millisekunde und koordinierte Weltzeit (Coordinated Universal Time, UTC) oder Ortszeit für den angegebenen Kalender.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

Initialisiert eine neue Instanz der DateTime-Struktur mit den angegebenen Werten für Jahr, Monat, Tag, Stunde, Minute, Sekunde, Millisekunde und koordinierte Weltzeit (Coordinated Universal Time, UTC) oder Ortszeit.

System_CAPS_pubmethodDateTime(Int64)

Initialisiert eine neue Instanz der DateTime-Struktur mit einer angegebenen Anzahl von Ticks.

System_CAPS_pubmethodDateTime(Int64, DateTimeKind)

Initialisiert eine neue Instanz der DateTime-Struktur mit einer angegebenen Anzahl von Ticks und koordinierter Weltzeit (UTC) oder lokaler Zeit.

NameBeschreibung
System_CAPS_pubpropertyDate

Ruft die Datumskomponente dieser Instanz ab.

System_CAPS_pubpropertyDay

Ruft den Tag des Monats ab, der durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyDayOfWeek

Ruft den Wochentag ab, der durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyDayOfYear

Ruft den Tag des Jahres ab, der durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyHour

Ruft die Komponente für die Stunden des Datums ab, das durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyKind

Ruft einen Wert ab, der angibt, ob die durch diese Instanz dargestellte Zeit auf lokaler Zeit, koordinierter Weltzeit (UTC) oder keinem von beiden basiert.

System_CAPS_pubpropertyMillisecond

Ruft die Komponente für die Millisekunden des Datums ab, das durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyMinute

Ruft die Komponente für die Minuten des Datums ab, das durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyMonth

Ruft die Komponente für den Monat des Datums ab, das durch diese Instanz dargestellt wird.

System_CAPS_pubpropertySystem_CAPS_staticNow

Ruft ein DateTime-Objekt ab, das auf das aktuelle Datum und die aktuelle Zeit auf dem lokalen Rechner als Ortszeit festgelegt ist.

System_CAPS_pubpropertySecond

Ruft die Komponente für die Sekunden des Datums ab, das durch diese Instanz dargestellt wird.

System_CAPS_pubpropertyTicks

Ruft die Anzahl der Ticks ab, die Datum und Uhrzeit dieser Instanz darstellen.

System_CAPS_pubpropertyTimeOfDay

Ruft die Uhrzeit für diese Instanz ab.

System_CAPS_pubpropertySystem_CAPS_staticToday

Ruft das aktuelle Datum ab.

System_CAPS_pubpropertySystem_CAPS_staticUtcNow

Ruft ein DateTime-Objekt ab, das auf die aktuelle Datums- und Uhrzeitangabe auf diesem Rechner als koordinierte Weltzeit (UTC) festgelegt ist.

System_CAPS_pubpropertyYear

Ruft die Komponente für das Jahr des Datums ab, das durch diese Instanz dargestellt wird.

NameBeschreibung
System_CAPS_pubmethodAdd(TimeSpan)

Gibt einen neuen DateTime-Wert zurück, der den Wert des angegebenen TimeSpan-Werts zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddDays(Double)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Tagen zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddHours(Double)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Stunden zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddMilliseconds(Double)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Millisekunden zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddMinutes(Double)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Minuten zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddMonths(Int32)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Monaten zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddSeconds(Double)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Sekunden zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddTicks(Int64)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Ticks zum Wert dieser Instanz addiert.

System_CAPS_pubmethodAddYears(Int32)

Gibt einen neuen DateTime-Wert zurück, der die angegebene Anzahl von Jahren zum Wert dieser Instanz addiert.

System_CAPS_pubmethodSystem_CAPS_staticCompare(DateTime, DateTime)

Vergleicht zwei Instanzen von DateTime und gibt eine ganze Zahl zurück, die angibt, ob die erste Instanz früher oder später als die zweite Instanz ist oder ob sie mit dieser identisch ist.

System_CAPS_pubmethodCompareTo(DateTime)

Vergleicht den Wert dieser Instanz mit einem angegebenen DateTime-Wert und gibt eine Ganzzahl zurück, die angibt, ob diese Instanz vor oder nach dem angegebenen DateTime-Wert liegt oder diesem entspricht.

System_CAPS_pubmethodCompareTo(Object)

Vergleicht den Wert dieser Instanz mit einem angegebenen Objekt, das einen angegebenen DateTime-Wert enthält, und gibt eine Ganzzahl zurück, die angibt, ob diese Instanz vor oder nach dem angegebenen DateTime-Wert liegt oder diesem entspricht.

System_CAPS_pubmethodSystem_CAPS_staticDaysInMonth(Int32, Int32)

Gibt die Anzahl der Tage im angegebenen Monat und Jahr zurück.

System_CAPS_pubmethodEquals(DateTime)

Gibt einen Wert zurück, der angibt, ob der Wert dieser Instanz gleich dem Wert der angegebenen DateTime-Instanz ist.

System_CAPS_pubmethodSystem_CAPS_staticEquals(DateTime, DateTime)

Gibt einen Wert zurück, der angibt, ob zwei DateTime-Instanzen denselben Datum- und Zeitwert besitzen.

System_CAPS_pubmethodEquals(Object)

Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.(Überschreibt ValueType.Equals(Object).)

System_CAPS_pubmethodSystem_CAPS_staticFromBinary(Int64)

Deserialisiert einen 64-Bit-Binärwert und erstellt ein ursprüngliches serialisiertes DateTime-Objekt neu.

System_CAPS_pubmethodSystem_CAPS_staticFromFileTime(Int64)

Konvertiert die angegebene Windows-Dateizeit in eine entsprechende Ortszeit.

System_CAPS_pubmethodSystem_CAPS_staticFromFileTimeUtc(Int64)

Konvertiert die angegebene Windows-Dateizeit in eine entsprechende UTC-Zeit.

System_CAPS_pubmethodSystem_CAPS_staticFromOADate(Double)

Gibt eine DateTime zurück, die dem angegebenen Datum für die OLE-Automatisierung entspricht.

System_CAPS_pubmethodGetDateTimeFormats()

Konvertiert den Wert dieser Instanz in alle Zeichenfolgendarstellungen, die von den Standardformatbezeichnern für Datum und Uhrzeit unterstützt werden.

System_CAPS_pubmethodGetDateTimeFormats(Char)

Konvertiert den Wert dieser Instanz in alle Zeichenfolgendarstellungen, die von den angegebenen Standardformatbezeichnern für Datum und Uhrzeit unterstützt werden.

System_CAPS_pubmethodGetDateTimeFormats(Char, IFormatProvider)

Konvertiert den Wert dieser Instanz in alle Zeichenfolgenentsprechungen, die von dem angegebenen Standardformatbezeichner für Datum und Uhrzeit und den angegebenen kulturspezifischen Formatierungsinformationen unterstützt werden.

System_CAPS_pubmethodGetDateTimeFormats(IFormatProvider)

Konvertiert den Wert dieser Instanz in alle Zeichenfolgendarstellungen, die von den Standardformatbezeichnern für Datum und Uhrzeit und den angegebenen kulturspezifischen Formatierungsinformationen unterstützt werden.

System_CAPS_pubmethodGetHashCode()

Gibt den Hashcode für diese Instanz zurück.(Überschreibt ValueType.GetHashCode().)

System_CAPS_pubmethodGetType()

Ruft den Type der aktuellen Instanz ab.(Geerbt von „Object“.)

System_CAPS_pubmethodGetTypeCode()

Gibt den TypeCode für den Werttyp DateTime zurück.

System_CAPS_pubmethodIsDaylightSavingTime()

Gibt an, ob sich diese Instanz von DateTime im Sommerzeitbereich für die aktuelle Zeitzone befindet.

System_CAPS_pubmethodSystem_CAPS_staticIsLeapYear(Int32)

Gibt eine Angabe darüber zurück, ob das angegebene Jahr ein Schaltjahr ist.

System_CAPS_pubmethodSystem_CAPS_staticParse(String)

Konvertiert die Zeichenfolgendarstellung einer Datums- und Uhrzeitangabe in die entsprechende DateTime.

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider)

Konvertiert die Zeichenfolgendarstellungen einer Datums- und Uhrzeitangabe unter Verwendung der kulturspezifischen Formatierungsinformationen in die entsprechende DateTime.

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider, DateTimeStyles)

Konvertiert die Zeichenfolgendarstellung einer Datums- und Uhrzeitangabe unter Verwendung der kulturspezifischen Formatierungsinformationen und Formatierungsstil in die entsprechende DateTime.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider)

Konvertiert die angegebene Zeichenfolgenentsprechung einer Datums- und Uhrzeitangabe unter Verwendung des angegebenen Formats und der angegebenen kulturabhängigen Formatierungsinformationen in die entsprechende DateTime. Das Format der Zeichenfolgendarstellung muss dem angegebenen Format genau entsprechen.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider, DateTimeStyles)

Konvertiert die angegebene Zeichenfolgenentsprechung einer Datums- und Uhrzeitangabe unter Verwendung der Angaben über Format, kulturabhängige Formatierungsinformationen und Stil in die entsprechende DateTime. Das Format der Zeichenfolgendarstellung muss dem angegebenen Format genau entsprechen. Andernfalls wird eine Ausnahme ausgelöst.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String[], IFormatProvider, DateTimeStyles)

Konvertiert die angegebene Zeichenfolgenentsprechung einer Datums- und Uhrzeitangabe unter Verwendung des angegebenen Formatarrays, der kulturspezifischen Formatierungsinformationen und des Stils in die DateTime-Entsprechung. Das Format der Zeichenfolgendarstellung muss mindestens einem der angegebenen Formate genau entsprechen. Andernfalls wird eine Ausnahme ausgelöst.

System_CAPS_pubmethodSystem_CAPS_staticSpecifyKind(DateTime, DateTimeKind)

Erstellt ein neues DateTime-Objekt, das über die gleiche Anzahl von Ticks wie die angegebene DateTime verfügt, aber entsprechend dem DateTimeKind-Wert in Ortszeit, koordinierter Weltzeit (Coordinated Universal Time, UTC) oder keinem von beiden angegeben ist.

System_CAPS_pubmethodSubtract(DateTime)

Subtrahiert die angegebene Datums- und Uhrzeitangabe von dieser Instanz.

System_CAPS_pubmethodSubtract(TimeSpan)

Subtrahiert die angegebene Dauer von dieser Instanz.

System_CAPS_pubmethodToBinary()

Serialisiert das aktuelle DateTime-Objekt in einen 64-Bit-Binärwert, der dann zum erneuten Erstellen des DateTime-Objekts verwendet werden kann.

System_CAPS_pubmethodToFileTime()

Konvertiert den Wert des aktuellen DateTime-Objekts in eine Windows-Dateizeit.

System_CAPS_pubmethodToFileTimeUtc()

Konvertiert den Wert des aktuellen DateTime-Objekts in eine Windows-Dateizeit.

System_CAPS_pubmethodToLocalTime()

Konvertiert den Wert des aktuellen DateTime-Objekts in die Ortszeit.

System_CAPS_pubmethodToLongDateString()

Konvertiert den Wert des aktuellen DateTime-Objekts in die entsprechende Zeichenfolgendarstellung im langen Datumsformat.

System_CAPS_pubmethodToLongTimeString()

Konvertiert den Wert des aktuellen DateTime-Objekts in die entsprechende Zeichenfolgendarstellung im langen Zeitformat.

System_CAPS_pubmethodToOADate()

Konvertiert den Wert dieser Instanz in das entsprechende Datum für OLE-Automatisierung.

System_CAPS_pubmethodToShortDateString()

Konvertiert den Wert des aktuellen DateTime-Objekts in die entsprechende Zeichenfolgendarstellung im kurzen Datumsformat.

System_CAPS_pubmethodToShortTimeString()

Konvertiert den Wert des aktuellen DateTime-Objekts in die entsprechende Zeichenfolgendarstellung im kurzen Zeitformat.

System_CAPS_pubmethodToString()

Konvertiert den Wert des aktuellen DateTime-Objekts unter Verwendung der Formatierungskonventionen der aktuellen Kultur in die entsprechende Zeichenfolgendarstellung.(Überschreibt ValueType.ToString().)

System_CAPS_pubmethodToString(IFormatProvider)

Konvertiert den Wert des aktuellen DateTime-Objekts unter Verwendung der angegebenen kulturspezifischen Formatierungsinformationen in die entsprechende Zeichenfolgendarstellung.

System_CAPS_pubmethodToString(String)

Konvertiert den Wert des aktuellen DateTime-Objekts unter Verwendung des angegebenen Formats und der Formatierungskonventionen der aktuellen Kultur in die entsprechende Zeichenfolgendarstellung.

System_CAPS_pubmethodToString(String, IFormatProvider)

Konvertiert den Wert des aktuellen DateTime-Objekts unter Verwendung des angegebenen Formats sowie der kulturabhängigen Formatierungsinformationen in die entsprechende Zeichenfolgendarstellung.

System_CAPS_pubmethodToUniversalTime()

Konvertiert den Wert des aktuellen DateTime-Objekts in koordinierte Weltzeit (UTC).

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, DateTime)

Konvertiert die angegebene Zeichenfolgendarstellung einer Datums- und Uhrzeitangabe in deren DateTime-Entsprechung und gibt einen Wert zurück, der angibt, ob die Konvertierung erfolgreich ausgeführt wurde.

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, IFormatProvider, DateTimeStyles, DateTime)

Konvertiert die angegebene Zeichenfolgendarstellung einer Datums- und Uhrzeitangabe unter Verwendung der angegebenen kulturspezifischen Formatierungsinformationen und des Formatierungsstils in die entsprechende DateTime und gibt einen Wert zurück, der angibt, ob die Konvertierung erfolgreich abgeschlossen wurde.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

Konvertiert die angegebene Zeichenfolgenentsprechung einer Datums- und Uhrzeitangabe unter Verwendung der Angaben über Format, kulturabhängige Formatierungsinformationen und Stil in die entsprechende DateTime. Das Format der Zeichenfolgendarstellung muss dem angegebenen Format genau entsprechen. Die Methode gibt einen Wert zurück, der angibt, ob die Konvertierung erfolgreich abgeschlossen wurde.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

Konvertiert die angegebene Zeichenfolgenentsprechung einer Datums- und Uhrzeitangabe unter Verwendung des angegebenen Formatarrays, der kulturspezifischen Formatierungsinformationen und des Stils in die DateTime-Entsprechung. Das Format der Zeichenfolgendarstellung muss mindestens einem der angegebenen Formate genau entsprechen. Die Methode gibt einen Wert zurück, der angibt, ob die Konvertierung erfolgreich abgeschlossen wurde.

NameBeschreibung
System_CAPS_pubfieldSystem_CAPS_staticMaxValue

Stellt den größtmöglichen Wert von DateTime dar. Dieses Feld ist schreibgeschützt.

System_CAPS_pubfieldSystem_CAPS_staticMinValue

Stellt den kleinstmöglichen Wert von DateTime dar. Dieses Feld ist schreibgeschützt.

NameBeschreibung
System_CAPS_puboperatorSystem_CAPS_staticAddition(DateTime, TimeSpan)

Addiert ein angegebenes Zeitintervall zu einer Datums- und Uhrzeitangabe und gibt eine neue Datums- und Uhrzeitangabe zurück.

System_CAPS_puboperatorSystem_CAPS_staticEquality(DateTime, DateTime)

Bestimmt, ob zwei angegebene Instanzen von DateTime gleich sind.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThan(DateTime, DateTime)

Bestimmt, ob eine angegebene DateTime später als eine andere angegebene DateTime ist.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThanOrEqual(DateTime, DateTime)

Bestimmt, ob eine vorliegende DateTime-Angabe eine Datums- und Uhrzeitangabe darstellt, die gleichzeitig oder später als eine andere vorliegende DateTime-Angabe ist.

System_CAPS_puboperatorSystem_CAPS_staticInequality(DateTime, DateTime)

Bestimmt, ob zwei angegebene Instanzen von DateTime nicht gleich sind.

System_CAPS_puboperatorSystem_CAPS_staticLessThan(DateTime, DateTime)

Bestimmt, ob eine angegebene DateTime früher als eine andere angegebene DateTime ist.

System_CAPS_puboperatorSystem_CAPS_staticLessThanOrEqual(DateTime, DateTime)

Bestimmt, ob eine vorliegende DateTime-Angabe eine Datums- und Uhrzeitangabe darstellt, die gleichzeitig oder früher als eine andere vorliegende DateTime-Angabe ist.

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, DateTime)

Subtrahiert eine Datums- und Uhrzeitangabe von einer anderen Datums- und Uhrzeitangabe und gibt ein Zeitintervall zurück.

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, TimeSpan)

Subtrahiert ein angegebenes Zeitintervall von einer Datums- und Uhrzeitangabe und gibt eine neue Datums- und Uhrzeitangabe zurück.

NameBeschreibung
System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToBoolean(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToByte(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToChar(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDateTime(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Gibt das aktuelle DateTime-Objekt zurück.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDecimal(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDouble(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt16(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt32(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt64(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSByte(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSingle(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToType(Type, IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert das aktuelle DateTime-Objekt in ein Objekt vom angegebenen Typ.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt16(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt32(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt64(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Diese Konvertierung wird nicht unterstützt. Bei dem Versuch der Verwendung dieser Methode wird eine InvalidCastException ausgelöst.

System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)

Füllt ein SerializationInfo-Objekt mit den für das Serialisieren des aktuellen DateTime-Objekts erforderlichen Daten.

System_CAPS_noteHinweis

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource-beta.microsoft.com/#mscorlib/system/datetime.cs#df6b1eba7461813b. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the T:System.Globalization.GregorianCalendar calendar (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight. A T:System.DateTime value is always expressed in the context of an explicit or default calendar.

System_CAPS_noteHinweis

If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the F:System.TimeSpan.TicksPerDay, F:System.TimeSpan.TicksPerHour, F:System.TimeSpan.TicksPerMinute, F:System.TimeSpan.TicksPerSecond, or F:System.TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the P:System.DateTime.Second component of a T:System.DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

In this section:

Instantiating a DateTime object
DateTime values and their string representations
Converting strings to DateTime values
Version considerations
DateTime values
DateTime operations
DateTime resolution
DateTime vs. TimeSpan
DateTime values and calendars
Persisting DateTime values
COM interop considerations

You can create a new T:System.DateTime value in any of the following ways:

  • By calling any of the overloads of the T:System.DateTime constructor that allow you to specify specific elements of the date and time value (such as the year, month, and day, or the number of ticks). The following statement illustrates a call to one of the T:System.DateTime constructors to create a date with a specific year, month, day, hour, minute, and second.

    DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
    
  • By using any compiler-specific syntax for declaring date and time values. For example, the following Visual Basic statement initializes a new T:System.DateTime value.

    Dim date1 As Date = #5/1/2008 8:30:52AM#
    
  • By assigning the T:System.DateTime object a date and time value returned by a property or method. The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new T:System.DateTime variables.

    DateTime date1 = DateTime.Now;
    DateTime date2 = DateTime.UtcNow;
    DateTime date3 = DateTime.Today;
    
  • By parsing the string representation of a date and time value. The Overload:System.DateTime.Parse, Overload:System.DateTime.ParseExact, Overload:System.DateTime.TryParse, and Overload:System.DateTime.TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the M:System.DateTime.Parse(System.String,System.IFormatProvider) method to parse a string and convert it to a T:System.DateTime value.

    string dateString = "5/1/2008 8:30:52 AM";
    DateTime date1 = DateTime.Parse(dateString, 
                              System.Globalization.CultureInfo.InvariantCulture); 
    

    Note that the Overload:System.DateTime.TryParse and Overload:System.DateTime.TryParseExact methods indicate whether a particular string contains a valid representation of a T:System.DateTime value in addition to performing the conversion.

  • By calling the T:System.DateTime structure's implicit default constructor. (For details on the implicit default constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers that support it, is declaring a T:System.DateTime value without explicitly assigning a date and time to it. The following example illustrates a call to the T:System.DateTime implicit default constructor in C# and Visual Basic, as well as a T:System.DateTime variable declaration with no assignment in Visual Basic.

    DateTime dat1 = new DateTime();
    // The following method call displays 1/1/0001 12:00:00 AM.
    Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
    // The following method call displays True.
    Console.WriteLine(dat1.Equals(DateTime.MinValue));
    

Internally, all T:System.DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual T:System.DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a T:System.DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the T:System.DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its Overload:System.DateTime.ToString method. The default M:System.DateTime.ToString method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default M:System.DateTime.ToString method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString());
// For en-US culture, displays 3/1/2008 7:00:00 AM

The M:System.DateTime.ToString(System.IFormatProvider) method returns the string representation of a date and time value using the short date and long time pattern of a specific culture. The following example uses the M:System.DateTime.ToString(System.IFormatProvider) method to display the date and time using the short date and long time pattern for the fr-FR culture.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 01/03/2008 07:00:00

The M:System.DateTime.ToString(System.String) method returns the string representation of the date and time in a format defined by a standard or custom format specifier and using the formatting conventions of the current culture. The following example uses the M:System.DateTime.ToString(System.String) method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM

The M:System.DateTime.ToString(System.String,System.IFormatProvider) method returns the string representation of the date and time in a format defined by a specific format specifier and using the formatting conventions of a specific culture. The following example uses the M:System.DateTime.ToString(System.String,System.IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR")));
// Displays samedi 1 mars 2008 07:00:00

For more information about formatting T:System.DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Parsing involves converting the string representation of a date and time to a T:System.DateTime value. Typically, date and time strings have two different usages in applications:

  • They represent a date and time that can take a variety of forms and that reflect the conventions of either the current culture or a specific culture. For example, an application may allow a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013", and allow a user whose current culture is en-GB to input a date value as "15/12/2013" or "15 December 2013".

  • They represent a date and time in a predefined format. For example, an application may serialize a date as "20130103" independently of the culture on which the app is running, or it may require that a date be input in the current culture's short date format.

You can use the M:System.DateTime.Parse(System.String) or M:System.DateTime.TryParse(System.String,System.DateTime@) method to convert a string that might reflect one of the common date and time formats used by a culture to a T:System.DateTime value. The following example shows how you can use M:System.DateTime.TryParse(System.String,System.DateTime@) to convert date strings in a number of different culture-specific formats to a T:System.DateTime value. It changes the current culture to English (Great Britain) and calls the M:System.DateTime.GetDateTimeFormats method to generate an array of date and time strings. It then passes each element in the array to the M:System.DateTime.TryParse(System.String,System.DateTime@) method. The output from the example shows that the parsing method was able to successfully convert each of the culture-specific date and time strings.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      DateTime date1 = new DateTime(2013, 6, 1, 12, 32, 30);
      List<string> badFormats = new List<String>();

      Console.WriteLine("{0,-37} {1,-19}\n", "Date String", "Date");
      foreach (var dateString in date1.GetDateTimeFormats()) {
         DateTime parsedDate;
         if (DateTime.TryParse(dateString, out parsedDate))
            Console.WriteLine("{0,-37} {1,-19}", dateString, DateTime.Parse(dateString));
         else
            badFormats.Add(dateString);
      } 

      // Display strings that could not be parsed.
      if (badFormats.Count > 0) {
         Console.WriteLine("\nStrings that could not be parsed: ");
         foreach (var badFormat in badFormats)
            Console.WriteLine("   {0}", badFormat);         
      }
   }
}
// The example displays the following output:
//       Date String                           Date               
//       
//       01/06/2013                            01/06/2013 00:00:00
//       01/06/13                              01/06/2013 00:00:00
//       1/6/13                                01/06/2013 00:00:00
//       1.6.13                                01/06/2013 00:00:00
//       2013-06-01                            01/06/2013 00:00:00
//       01 June 2013                          01/06/2013 00:00:00
//       1 June 2013                           01/06/2013 00:00:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       01 June                               01/06/2013 00:00:00
//       01 June                               01/06/2013 00:00:00
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       2013-06-01T12:32:30                   01/06/2013 12:32:30
//       12:32                                 22/04/2013 12:32:00
//       12:32                                 22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       2013-06-01 12:32:30Z                  01/06/2013 05:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 07:32:30 PM              01/06/2013 19:32:30
//       01 June 2013 7:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 07:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 7:32:30 PM                01/06/2013 19:32:30
//       June 2013                             01/06/2013 00:00:00
//       June 2013                             01/06/2013 00:00:00

You can use the M:System.DateTime.TryParse(System.String,System.DateTime@) and M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods to convert a date and time string that must match a particular format or formats to a T:System.DateTime value. You specify the required format or formats as a parameter to the parsing methodby using one or more or date and time format strings. The following example uses the M:System.DateTime.TryParseExact(System.String,System.String[],System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to T:System.DateTime values.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats = { "yyyyMMdd", "HHmmss" };
      string[] dateStrings = { "20130816", "20131608", "  20130816   ", 
                               "115216", "521116", "  115216  " };
      DateTime parsedDate;

      foreach (var dateString in dateStrings) {
         if (DateTime.TryParseExact(dateString, formats, null, 
                                    DateTimeStyles.AllowWhiteSpaces |
                                    DateTimeStyles.AdjustToUniversal,
                                    out parsedDate))
            Console.WriteLine("{0} --> {1:g}", dateString, parsedDate);
         else
            Console.WriteLine("Cannot convert {0}", dateString);
      }
   }
}
// The example displays the following output:
//       20130816 --> 8/16/2013 12:00 AM
//       Cannot convert 20131608
//         20130816    --> 8/16/2013 12:00 AM
//       115216 --> 4/22/2013 11:52 AM
//       Cannot convert 521116
//         115216   --> 4/22/2013 11:52 AM

The M:System.DateTime.Parse(System.String) and M:System.DateTime.ParseExact(System.String,System.String,System.IFormatProvider) methods throw an exception if the string to be converted to a T:System.DateTime value cannot be parsed. The M:System.DateTime.TryParse(System.String,System.DateTime@) and M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods return a T:System.Boolean value that indicates whether the conversion succeeded or failed. Because the parsing operation for date and time strings, particularly if strings are input by users, tends to have a high failure rate, and because exception handling is expensive, you should use the M:System.DateTime.TryParse(System.String,System.DateTime@) or M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods in scenarios where performance is important or conversions are subject to a high rate of failure.

For more information about parsing date and time values, see Parsing Date and Time Strings in the .NET Framework.

Prior to the .NET Framework version 2.0, the T:System.DateTime structure contains a 64-bit field composed of an unused 2-bit field concatenated with a private Ticks field, which is a 62-bit unsigned field that contains the number of ticks that represent the date and time. The value of the Ticks field can be obtained with the P:System.DateTime.Ticks property.

Starting with the .NET Framework 2.0, the T:System.DateTime structure contains a 64-bit field composed of a private Kind field concatenated with the Ticks field. The Kind field is a 2-bit field that indicates whether the T:System.DateTime structure represents a local time, a Coordinated Universal Time (UTC), or the time in an unspecified time zone. The Kind field is used when performing time conversions between time zones, but not for time comparisons or arithmetic. The value of the Kind field can be obtained with the P:System.DateTime.Kind property.

System_CAPS_noteHinweis

An alternative to the T:System.DateTime structure for working with date and time values in particular time zones is the T:System.DateTimeOffset structure. The T:System.DateTimeOffset structure stores date and time information in a private T:System.DateTime field and the number of minutes by which that date and time differs from UTC in a private T:System.Int16 field. This makes it possible for a T:System.DateTimeOffset value to reflect the time in a particular time zone, whereas a T:System.DateTime value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the T:System.DateTime structure or the T:System.DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.

Descriptions of time values in the T:System.DateTime type are often expressed using the Coordinated Universal Time (UTC) standard, which is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is not applicable to UTC.

Local time is relative to a particular time zone. A time zone is associated with a time zone offset, which is the displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally affected by daylight saving time, which adds or subtracts an hour from the length of a day. Consequently, local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The time zone offset at the UTC origin point is zero.

UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones.

If the P:System.DateTime.Kind property of a T:System.DateTime object is F:System.DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone.

A calculation using a T:System.DateTime structure, such as M:System.DateTime.Add(System.TimeSpan) or M:System.DateTime.Subtract(System.DateTime), does not modify the value of the structure. Instead, the calculation returns a new T:System.DateTime structure whose value is the result of the calculation.

Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not.

The T:System.DateTime structure itself offers limited support for converting from one time zone to another. You can use the M:System.DateTime.ToLocalTime method to convert UTC to local time, or you can use the M:System.DateTime.ToUniversalTime method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the T:System.TimeZoneInfo class. Using these methods, you can convert the time in any one of the world's time zones to the time in any other time zone.

Calculations and comparisons of T:System.DateTime objects are meaningful only if the objects represent times in the same time zone. You can use a T:System.TimeZoneInfo object to represent a T:System.DateTime value's time zone, although the two are loosely coupled. (That is, a T:System.DateTime object does not have a property that returns an object that represents that date and time value's time zone other than the P:System.DateTime.Kind property.) For this reason, in a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a T:System.DateTime object was created. For example, you could use a structure that wraps both the T:System.DateTime value and the T:System.TimeZoneInfo object that represents the T:System.DateTime value's time zone. For details on using UTC in calculations and comparisons with T:System.DateTime values, see Performing Arithmetic Operations with Dates and Times.

Each T:System.DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of constructors that specify a calendar, and methods with a parameter derived from T:System.IFormatProvider, such as T:System.Globalization.DateTimeFormatInfo, that implicitly specifies a calendar.

Operations by members of the T:System.DateTime type take into account details such as leap years and the number of days in a month.

Two other common operations with T:System.DateTime values involve converting a date and time value to or from its string representation. The process of converting a T:System.DateTime value to its string representation is a formatting operation; for more information about formatting, see DateTime values and their string representations. The process of converting the string representation of a date and time to a T:System.DateTime value is a parsing operation; for more information about parsing, see Converting strings to DateTime values.

System_CAPS_noteHinweis

As an alternative to performing date and time arithmetic on T:System.DateTime values to measure elapsed time, you can use the T:System.Diagnostics.Stopwatch class.

The P:System.DateTime.Ticks property expresses date and time values in units of one ten-millionth of a second, and the P:System.DateTime.Millisecond property returns the thousandths of a second in a date and time value. However, if you are using repeated calls to the P:System.DateTime.Now property to measure elapsed time, and you are concerned with small time intervals less than 100 milliseconds, you should note that values returned by the P:System.DateTime.Now property are dependent on the system clock, which on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds.

The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the M:System.Threading.Thread.Sleep(System.Int32) method introduces a five millisecond delay. As the output from the example shows, the number of milliseconds in returned by the DateTime.Now.Milliseconds property changed only after the call to M:System.Threading.Thread.Sleep(System.Int32).

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      String output = "";
      for (int ctr = 0; ctr <= 20; ctr++) {
         output += String.Format("{0}\n", DateTime.Now.Millisecond);
         // Introduce a delay loop.
         for (int delay = 0; delay <= 1000; delay++)
         {}

         if (ctr == 10) {
            output += "Thread.Sleep called...\n";
            Thread.Sleep(5);
         }
      }
      Console.WriteLine(output);
   }
}
// The example displays the following output:
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       Thread.Sleep called...
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143

The T:System.DateTime and T:System.TimeSpan value types differ in that a T:System.DateTime represents an instant in time whereas a T:System.TimeSpan represents a time interval. This means, for example, that you can subtract one instance of T:System.DateTime from another to obtain a T:System.TimeSpan object that represents the time interval between them. Or you could add a positive T:System.TimeSpan to the current T:System.DateTime to obtain a T:System.DateTime value that represents a future date.

You can add or subtract a time interval from a T:System.DateTime object. Time intervals can be negative or positive, can be expressed in units such as ticks or seconds, or can be expressed as a T:System.TimeSpan object.

The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the T:System.Globalization.Calendar class. They are:

  • The T:System.Globalization.ChineseLunisolarCalendar class.

  • The T:System.Globalization.EastAsianLunisolarCalendar class.

  • The T:System.Globalization.GregorianCalendar class.

  • The T:System.Globalization.HebrewCalendar class.

  • The T:System.Globalization.HijriCalendar class.

  • The T:System.Globalization.JapaneseCalendar class.

  • The T:System.Globalization.JapaneseLunisolarCalendar class.

  • The T:System.Globalization.JulianCalendar class.

  • The T:System.Globalization.KoreanCalendar class.

  • The T:System.Globalization.KoreanLunisolarCalendar class.

  • The T:System.Globalization.PersianCalendar class.

  • The T:System.Globalization.TaiwanCalendar class.

  • The T:System.Globalization.TaiwanLunisolarCalendar class.

  • The T:System.Globalization.ThaiBuddhistCalendar class.

  • The T:System.Globalization.UmAlQuraCalendar class.

Each culture uses a default calendar defined by its read-only P:System.Globalization.CultureInfo.Calendar property and supports one or more calendars defined by its read-only P:System.Globalization.CultureInfo.OptionalCalendars property. The calendar currently used by a specific T:System.Globalization.CultureInfo object is defined by its P:System.Globalization.DateTimeFormatInfo.Calendar property; it must be one of the calendars found in the P:System.Globalization.CultureInfo.OptionalCalendars array.

A culture's current calendar is used in all formatting operations for that culture. For example, the default calendar of the Persian (Iran) culture is the Umm al-Qura calendar, which is represented by the T:System.Globalization.UmAlQuraCalendar class. When a T:System.Globalization.CultureInfo object that represents the Persian (Iran) culture is used in a date and time formatting operation, the Umm al-Qura calendar is used by default, and the Gregorian calendar is used only if the culture's P:System.Globalization.DateTimeFormatInfo.Calendar property is changed, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = new DateTime(2016, 5, 28);

      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
// 08/03/1395 12:00:00 ?.?
// 28/05/2016 12:00:00 ?.?

A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = DateTime.Parse("08/03/1395", faIR);
      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
//       08/03/1395 12:00:00 ?.?
//       28/05/2016 12:00:00 ?.?

You can also instantiate a T:System.DateTime value by using the date and time elements (such as the number of the year, month, and day) of a specific calendar by calling a DateTime constructor that includes a calendar parameter and passing it a P:System.Globalization.CultureInfo.Calendar object that represents that calendar. The following example does this by using the date and time elements from the T:System.Globalization.UmAlQuraCalendar calendar.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var dat = new DateTime(1395, 8, 18, faIR.DateTimeFormat.Calendar);
      Console.WriteLine("Umm-al-Qura date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Gregorian date:   {0:d}", dat);
   }
}
// The example displays the following output:
//       Umm-al-Qura date: 18/08/1395
//       Gregorian date:   11/8/2016

DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.

All other T:System.DateTime properties and methods use the Gregorian calendar. For example, the P:System.DateTime.Year property returns the year in the Gregorian calendar, and the M:System.DateTime.IsLeapYear(System.Int32) method assumes that the year parameter is a year in the Gregorian calendar. Each T:System.DateTime member that uses the Gregorian calendar has a corresponding member of the P:System.Globalization.CultureInfo.Calendar class that uses a specific calendar. For example, the M:System.Globalization.Calendar.GetYear(System.DateTime) method returns the year in a specific calendar, and the M:System.Globalization.Calendar.IsLeapYear(System.Int32) method interprets the year parameter as a year number in a specific calendar. The following example use both the T:System.DateTime and the corresponding members of the T:System.Globalization.UmAlQuraCalendar class.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var cal = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, cal);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Year: {0}", cal.GetYear(dat));
      Console.WriteLine("Leap year: {0}\n", 
                        cal.IsLeapYear(cal.GetYear(dat)));

      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Year: {0}", dat.Year);
      Console.WriteLine("Leap year: {0}", DateTime.IsLeapYear(dat.Year));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Year: 1395
//       Leap year: True
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Year: 2016
//       Leap year: True

Although the T:System.DateTime structure includes P:System.DateTime.DayOfWeek property that returns the day of the week in the Gregorian calendar, it does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar's M:System.Globalization.Calendar.GetWeekOfYear(System.DateTime,System.Globalization.CalendarWeekRule,System.DayOfWeek) method. The following example provides an illustration.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var umAlQura = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, umAlQura);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Day of Week: {0}", umAlQura.GetDayOfWeek(dat));
      Console.WriteLine("Week of year: {0}\n", 
                        umAlQura.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                               DayOfWeek.Sunday));

      var greg = new GregorianCalendar(); 
      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Day of Week: {0}", dat.DayOfWeek);
      Console.WriteLine("Week of year: {0}", 
                         greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                            DayOfWeek.Sunday));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Day of Week: Tuesday
//       Week of year: 34
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Day of Week: Tuesday
//       Week of year: 46

For more information on dates and calendars, see Working with Calendars.

You can persist T:System.DateTime values in four ways:

  • You can convert them to strings and persist the strings.

  • You can convert them to 64-bit integer values (the value of the P:System.DateTime.Ticks property) and persist the integers.

  • You canserialize the DateTime values.

  • You can serialize the DateTime values along with time zone information.

Regardless of which technique you choose, you must ensure that the routine that restores the T:System.DateTime values doesn't lose data or throw an exception. T:System.DateTime values should round-trip. That is, the original value and the restored value should be the same. And if the original T:System.DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.

To successfully restore T:System.DateTime values that are persisted as strings, follow these rules:

  • Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the M:System.DateTime.ToString(System.String,System.IFormatProvider)overload to save the string by using the conventions of the invariant culture, and call the M:System.DateTime.Parse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) overload to restore the string by using the conventions of the invariant culture. Never use the M:System.DateTime.ToString, M:System.DateTime.Parse(System.String), or M:System.DateTime.TryParse(System.String,System.DateTime@) overloads, which use the conventions of the current thread culture.

  • If the data represents a single moment of time, ensure that it represents the same moment in time when it's restored, even if it's restored on a system that uses a different time zone. To do this, you convert the T:System.DateTime value to Coordinated Universal Time (UTC) before saving it. You can also serialize the value along with time zone information; for more information about this approach, see Serializing DateTime and time zone data.

The most common error made when persisting T:System.DateTime values as strings is to rely on the formatting conventions of the default or current culture. Problems arise if the current culture is different when saving and restoring the strings. The following example illustrates these problems. It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). It restores the dates using the formatting conventions of the current culture, which in this case is English (Great Britain). Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\BadDates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToString() + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParse(inputValue, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", inputValue, dateValue);
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       Cannot parse //6/14/2014 6:32:00 AM//
//       //7/10/2014 11:49:00 PM// --> 07 October 2014 23:49
//       //1/10/2015 1:16:00 AM// --> 01 October 2015 01:16
//       Cannot parse //12/20/2014 9:45:00 PM//
//       //6/2/2014 3:14:00 PM// --> 06 February 2014 15:14
//       Restored dates...

To round-trip T:System.DateTime values successfully, follow these steps:

  1. If the values represent single moments of time, convert them from the local time to UTC by calling the M:System.DateTime.ToUniversalTime method.

  2. Convert the dates to their string representations by calling the M:System.DateTime.ToString(System.String,System.IFormatProvider) or M:System.String.Format(System.IFormatProvider,System.String,System.Object[]) overload. Use the formatting conventions of the invariant culture by specifying P:System.Globalization.CultureInfo.InvariantCulture as the provider argument. Specify that the value should round-trip by using the "O" or "R" .

  3. When you call the M:System.DateTime.Parse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) method.

To restore the persisted T:System.DateTime values without data loss, do the following:

  1. Parse the data by calling the M:System.DateTime.ParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) overload. Specify P:System.Globalization.CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. Include the F:System.Globalization.DateTimeStyles.RoundtripKind value in the styles argument.

  2. If the T:System.DateTime values represent single moments in time, call the M:System.DateTime.ToLocalTime method to convert the parsed date from UTC to local time.

The following example uses the invariant culture and the "O" standard format string to ensure that T:System.DateTime values that are saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\Dates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) 
                   + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture, 
                               DateTimeStyles.RoundtripKind, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", 
                              inputValue, dateValue.ToLocalTime());
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
//       '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
//       '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
//       '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
//       '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
//       Restored dates...

Instead of persisting a T:System.DateTime value as a string, you can persist it as an T:System.Int64 value that represents a number of ticks. In this case, you don't have to consider the culture of the systems the T:System.DateTime values are persisted and restored on.

To persist a T:System.DateTime value as an integer:

  • If the T:System.DateTime values represent single moments in time, convert them to UTC by calling the M:System.DateTime.ToUniversalTime method.

  • Retrieve the number of ticks represented by the T:System.DateTime value from its P:System.DateTime.Ticks property.

To restore a T:System.DateTime value that has been persisted as an integer:

  1. Instantiate a new T:System.DateTime object by passing the T:System.Int64 value to the M:System.DateTime.#ctor(System.Int64) constructor.

  2. If the T:System.DateTime value represents a single moment in time, convert it from UTC to the local time by calling the M:System.DateTime.ToLocalTime method.

The following example persists an array of T:System.DateTime values as integers on a system in the U.S. Pacific Time zone. It restores it on a system in the UTC zone. The file that contains the integers includes an T:System.Int32 value that indicates the total number of T:System.Int64 values that immediately follow it.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

class Example
{
   private const string filename = @".\IntDates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      long[] ticks = new long[dates.Length];
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         ticks[ctr] = dates[ctr].ToUniversalTime().Ticks; 
      }
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryWriter bw = new BinaryWriter(fs);
      bw.Write(ticks.Length);
      foreach (var tick in ticks)
         bw.Write(tick);

      bw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryReader br = new BinaryReader(fs);
      int items;
      DateTime[] dates;

      try { 
         items = br.ReadInt32();
         dates = new DateTime[items];

         for (int ctr = 0; ctr < items; ctr++) {
            long ticks = br.ReadInt64();
            dates[ctr] = new DateTime(ticks).ToLocalTime();
         }
      }   
      catch (EndOfStreamException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }   
      catch (IOException) {
         Console.WriteLine("Unspecified I/O error. Unable to restore data...");
         return;
      }
      // Thrown during array initialization.
      catch (OutOfMemoryException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }
      finally {      
         br.Close();
      }   

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

Instead of saving T:System.DateTime values as strings or integers, which you then have to convert back to T:System.DateTime values, you can persist T:System.DateTime values through serialization to a stream or file, and then restore them through deserialization. In this case, T:System.DateTimedata is serialized in some specified object format, and the objects are restored when they are deserialized. A formatter or serializer, such as T:System.Xml.Serialization.XmlSerializer or T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, handles the process of serialization and deserialization. For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization in the .NET Framework.

The following example uses the T:System.Xml.Serialization.XmlSerializer class to serialize and deserialize T:System.DateTime values that represent all leap year days in the twenty-first century. The output represents the result if the example is run on a system whose current culture is English (Great Britain). Because we've deserialized the T:System.DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Serialization;

class Example
{
   private const string filename = @".\LeapYears.xml";

   public static void Main()
   {
      // Serialize the data.
      List<DateTime> leapYears = new List<DateTime>();
      for (int year = 2000; year <= 2100; year += 4) {
         if (DateTime.IsLeapYear(year)) 
            leapYears.Add(new DateTime(year, 2, 29));
      }
      DateTime[] dateArray = leapYears.ToArray();

      XmlSerializer serializer = new XmlSerializer(dateArray.GetType());
      TextWriter sw = new StreamWriter(filename);

      try {
         serializer.Serialize(sw, dateArray);
      }
      catch (InvalidOperationException e) {
         Console.WriteLine(e.InnerException.Message);         
      }
      finally {
         if (sw != null) sw.Close();
      }   

      // Deserialize the data.
      DateTime[] deserializedDates;
      using (FileStream fs = new FileStream(filename, FileMode.Open)) {
         deserializedDates = (DateTime[]) serializer.Deserialize(fs);
      } 

      // Display the dates.
      Console.WriteLine("Leap year days from 2000-2100 on an {0} system:",
                        Thread.CurrentThread.CurrentCulture.Name);
      int nItems = 0;
      foreach (var dat in deserializedDates) {
         Console.Write("   {0:d}     ", dat);
         nItems++;
         if (nItems % 5 == 0) 
               Console.WriteLine(); 
      }
   }
}
// The example displays the following output:
//    Leap year days from 2000-2100 on an en-GB system:
//       29/02/2000       29/02/2004       29/02/2008       29/02/2012       29/02/2016
//       29/02/2020       29/02/2024       29/02/2028       29/02/2032       29/02/2036
//       29/02/2040       29/02/2044       29/02/2048       29/02/2052       29/02/2056
//       29/02/2060       29/02/2064       29/02/2068       29/02/2072       29/02/2076
//       29/02/2080       29/02/2084       29/02/2088       29/02/2092       29/02/2096

The previous example doesn't include time information. However, if a T:System.DateTime value represents a moment in time and is expressed as a local time, you should convert it from local time to UTC before serializing it by calling the M:System.DateTime.ToUniversalTime method. After you deserialize it, you should convert it from UTC to local time by calling the M:System.DateTime.ToLocalTime method. The following example uses the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class to serializeT:System.DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the UTC zone.

using System;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

class Example
{
   private const string filename = @".\Dates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryFormatter bin = new BinaryFormatter();

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         dates[ctr] = dates[ctr].ToUniversalTime();
      }
      bin.Serialize(fs, dates);
      fs.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryFormatter bin = new BinaryFormatter();
      DateTime[] dates = (DateTime[]) bin.Deserialize(fs);
      fs.Close();

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToLocalTime().ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

The previous examples have all assumed that T:System.DateTime values are expressed as local times, and converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. T:System.DateTime values may also reflect moments in time in a time zone other than local and UTC. In this case, because the T:System.DateTime structure is not time zone-aware, you have to serialize both the T:System.DateTimevalue and the T:System.TimeZoneInfo object that represents its time zone. To do this, create a type whose fields include both the T:System.DateTime value and its time zone. The following example defines a DateWithTimeZone structure that illustrates how this might be done.

using System;

namespace DateTimeExtensions
{
   [Serializable] public struct DateWithTimeZone
   {
      private TimeZoneInfo tz;
      private DateTime dt;

      public DateWithTimeZone(DateTime dateValue, TimeZoneInfo timeZone)
      {
         dt = dateValue;
         if (timeZone == null)
            tz = TimeZoneInfo.Local;
         else
            tz = timeZone;
      }   

      public TimeZoneInfo TimeZone 
      { get { return (tz); }
        set { tz = value; } }

      public DateTime DateTime 
      { get { return (dt); }
        set { dt = value; } }
   }
}
System_CAPS_importantWichtig

The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. To run the examples, first create a class library that contains the DateWithTimeZone structure, and then add a reference to it when you compile each example.

By using the DateWithTimeZone structure , you can then persist date and time along with time zone information. The following example uses the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class to serialize an array of DateWithTimeZoneobjects.

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   public static void Main()
   {
      DateWithTimeZone[] dates= { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                                  new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) };
      FileStream fs = new FileStream(@".\Schedule.bin", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      try {
         formatter.Serialize(fs, dates);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Serialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

The following example then calls the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream) method to deserialize it.

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   private const string filename = @".\Schedule.bin";

   public static void Main()
   {
      FileStream fs;
      if (File.Exists(filename))
         fs = new FileStream(filename, FileMode.Open);
      else {
         Console.WriteLine("Unable to find file to deserialize.");
         return;
      }

      BinaryFormatter formatter = new BinaryFormatter();
      DateWithTimeZone[] dates;
      try {
         dates = (DateWithTimeZone[]) formatter.Deserialize(fs);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Deserialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

A T:System.DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, a T:System.DateTime value that specifies only a time does not round-trip as you might expect.

If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M., instead of January, 1, 0001 C.E. at 3:00 P.M. This happens because the .NET Framework and COM assume a default date when only a time is specified. However, the COM system assumes a base date of December 30, 1899 C.E. while the .NET Framework assumes a base date of January, 1, 0001 C.E.

When only a time is passed from the .NET Framework to COM, special processing is performed that converts the time to the format used by COM. When only a time is passed from COM to the .NET Framework, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. This also means if a date starts its round-trip from COM, the .NET Framework and COM preserve the date.

The behavior of the .NET Framework and COM means that if your application round-trips a T:System.DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final T:System.DateTime object.

The following example demonstrates how to compare roughly equivalent T:System.DateTime values, accepting a small margin of difference when declaring them equal.

using System;

class DateTimeTester 
{
   static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds)
   {
      long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds 
                                                     % frequencyInSeconds;

      delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;

      return Math.Abs(delta) < windowInSeconds;
	}

	public static void Main() 
	{
      int window = 10;
      int freq = 60 * 60 * 2; // 2 hours;

      DateTime d1 = DateTime.Now;

      DateTime d2 = d1.AddSeconds(2 * window);
      DateTime d3 = d1.AddSeconds(-2 * window);
      DateTime d4 = d1.AddSeconds(window / 2);
      DateTime d5 = d1.AddSeconds(-window / 2);

      DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);
      DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
      DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
      DateTime d9 = (d1.AddHours(2)).AddSeconds(-window / 2);

      Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                        d1, d1, RoughlyEquals(d1, d1, window, freq));
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                        d1, d2, RoughlyEquals(d1, d2, window, freq));
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                        d1, d3, RoughlyEquals(d1, d3, window, freq));
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                        d1, d4, RoughlyEquals(d1, d4, window, freq));
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                        d1, d5, RoughlyEquals(d1, d5, window, freq));

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                        d1, d6, RoughlyEquals(d1, d6, window, freq));
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                        d1, d7, RoughlyEquals(d1, d7, window, freq));
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                        d1, d8, RoughlyEquals(d1, d8, window, freq));
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                        d1, d9, RoughlyEquals(d1, d9, window, freq));
	}
}
// The example displays output similar to the following:
//    d1 (1/28/2010 9:01:26 PM) ~= d1 (1/28/2010 9:01:26 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d2 (1/28/2010 9:01:46 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d3 (1/28/2010 9:01:06 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d4 (1/28/2010 9:01:31 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d5 (1/28/2010 9:01:21 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d6 (1/28/2010 11:01:46 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d7 (1/28/2010 11:01:06 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d8 (1/28/2010 11:01:31 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d9 (1/28/2010 11:01:21 PM): True

Universelle Windows-Plattform
Verfügbar seit 8
.NET Framework
Verfügbar seit 1.1
Portierbare Klassenbibliothek
Unterstützt in: portierbare .NET-Plattformen
Silverlight
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
Windows Phone
Verfügbar seit 8.1

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

System_CAPS_cautionAchtung

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

Zurück zum Anfang
Anzeigen: