Little Miracles C # /. NET - DateTimeOffset Structure
Let's consider some parts of the .Net Framework that look trivial, but are quite capable of making your code simpler both in writing and in maintenance.
Those writing in .NET (and if you do not do it, then reading this post in vain) will probably use the DateTime structure from time to time for their needs. This structure is convenient for storing dates, times or dates / times related to the local time zone (or to UTC).
However, there are times when you need to save the time as an offset, and not convert it to local time. And here, the structure that first appeared in .NET 3.5 - DateTimeOffset - will come to your aid.
Problem: parsing DateTime can lead to conversion to local time
Imagine that you are using a file, web service, etc. some third-party company whose servers are in a different time zone. Moreover, they have several fields in the returned data, which should contain dates, but actually contain serialized instances of the DateTime structure, the time in which is set at midnight. For example, they give the patient’s birth date in the following form:
2012-03-01 00: 00: 00-05: 00
This record indicates that the person was born on March 1, 2012 at an unspecified time (after all, most of the forms does not require you to fill in the time of your birth). But since an instance of the DateTime structure was serialized “head-on”, it contains the time set at midnight according to its time zone.
So, knowing that this date is compatible with the Eastern Time Zone, and we are in the Central Time Zone, we parse it like this: It looks perfect, doesn't it? But here lies the problem. If we check the contents of the DateTime object on our local machine where the Central time zone is set, we will see this: 2012-02-29 11:00:00 PM What happened? (Or as one character said - Who did this?) Yes, the DateTime.Parse () method converted the date to a local time zone since the original date of birth was stored with the specified offset. They just provided you a service - they converted the specified date and time into your local date and time. This is not so bad if it were not about the birthday, which from March 1 moved to February 29.
Of course, we can phone the third party and ask to stop including time in the date line or stop sending the offset along with the time (in this case, it will not be converted to local time, but will be marked as DateTimeKind.Unspecified).
However, it happens that we do not have the opportunity to make a difference in this way.
There are times when you want to read the date and time with an offset, but not convert it to a local time zone. And here DateTimeOffset comes in handy.
DateTimeOffset - stores DateTime and Offset
So what about DateTimeOffset? The structure is as simple as its name, DateTimeOffset is date + time + offset. That is why it represents a much more accurate point in time, because it includes information about the offset at which the current date and time were set.
In truth, the functionality of DateTime and DateTimeOffset overlaps in many ways, and since Microsoft has a guide for choosing one or the other, I recommend that you familiarize yourself with it on MSDN. The article is entitled “Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo”.
In general, you can use DateTime if you are “attached” to the same time zone or use only universal time in UTC. But if you want to use dates and times from different time zones, and also want to save offset information without converting to local time, then it is better to use DateTimeOffset.
The DateTimeOffset structure has many of the same properties as the DateTime structure (Day, Month, Year, Hour, Minute, Second, etc.), so I won’t describe them here. The main difference is a few new properties:
DateTime
Returns a DateTime without offset.
LocalDateTime
Returns the converted DateTime, taking into account the offset (i.e., in the local time zone).
Offset
Returns the offset relative to UTC.
UtcDateTime
Returns a DateTime as UTC time.
The DateTime property returns you a DateTime (not cast to the local time zone), and the Offset property has the TimeSpan format, which represents the offset from UTC. There are also LocalDateTime and UtcDateTime properties that convert the given DateTimeOffset to DateTime for the local time zone or UTC.
I also note that the Now and UtcNow properties of the DateTimeOffset structure do not return the DateTime type, but DateTimeOffsets with the corresponding offset from UTC. Of course, like DateTime, DateTimeOffset has methods that deal with date / time, returning the DateTimeOffset type instead of DateTime.
So how does all this help us in the above example? Now we know that the third party sends us the date and time of its time zone, which does not need to be converted to a local date / time. Therefore, you can use DateTimeOffset.Parse () (or TryParse ()) and select only the date: Thus, you can easily parse dates without having to track the “midnight shift” or use it where you need to have a date, time and offset without conversion at local time. Results Although the DateTime structure is quite powerful in terms of parsing, manipulating and comparing dates / times, it can deliver a lot of unpleasant minutes in working with dates in the format of different time zones. DateTimeOffset in this case is much more flexible, since it uses an offset from UTC.
Free translation (c) by V.F. Alien aka hDrummer, original here .
Those writing in .NET (and if you do not do it, then reading this post in vain) will probably use the DateTime structure from time to time for their needs. This structure is convenient for storing dates, times or dates / times related to the local time zone (or to UTC).
However, there are times when you need to save the time as an offset, and not convert it to local time. And here, the structure that first appeared in .NET 3.5 - DateTimeOffset - will come to your aid.
Problem: parsing DateTime can lead to conversion to local time
Imagine that you are using a file, web service, etc. some third-party company whose servers are in a different time zone. Moreover, they have several fields in the returned data, which should contain dates, but actually contain serialized instances of the DateTime structure, the time in which is set at midnight. For example, they give the patient’s birth date in the following form:
2012-03-01 00: 00: 00-05: 00
This record indicates that the person was born on March 1, 2012 at an unspecified time (after all, most of the forms does not require you to fill in the time of your birth). But since an instance of the DateTime structure was serialized “head-on”, it contains the time set at midnight according to its time zone.
So, knowing that this date is compatible with the Eastern Time Zone, and we are in the Central Time Zone, we parse it like this: It looks perfect, doesn't it? But here lies the problem. If we check the contents of the DateTime object on our local machine where the Central time zone is set, we will see this: 2012-02-29 11:00:00 PM What happened? (Or as one character said - Who did this?) Yes, the DateTime.Parse () method converted the date to a local time zone since the original date of birth was stored with the specified offset. They just provided you a service - they converted the specified date and time into your local date and time. This is not so bad if it were not about the birthday, which from March 1 moved to February 29.
// ясно что здесь выполняется чтение файла/потока/и т.п.
var dateString = "2012-03-01 00:00:00-05:00";
// парсим в DateTime
var birthDay = DateTime.Parse(dateString);
Of course, we can phone the third party and ask to stop including time in the date line or stop sending the offset along with the time (in this case, it will not be converted to local time, but will be marked as DateTimeKind.Unspecified).
However, it happens that we do not have the opportunity to make a difference in this way.
There are times when you want to read the date and time with an offset, but not convert it to a local time zone. And here DateTimeOffset comes in handy.
DateTimeOffset - stores DateTime and Offset
So what about DateTimeOffset? The structure is as simple as its name, DateTimeOffset is date + time + offset. That is why it represents a much more accurate point in time, because it includes information about the offset at which the current date and time were set.
In truth, the functionality of DateTime and DateTimeOffset overlaps in many ways, and since Microsoft has a guide for choosing one or the other, I recommend that you familiarize yourself with it on MSDN. The article is entitled “Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo”.
In general, you can use DateTime if you are “attached” to the same time zone or use only universal time in UTC. But if you want to use dates and times from different time zones, and also want to save offset information without converting to local time, then it is better to use DateTimeOffset.
The DateTimeOffset structure has many of the same properties as the DateTime structure (Day, Month, Year, Hour, Minute, Second, etc.), so I won’t describe them here. The main difference is a few new properties:
DateTime
Returns a DateTime without offset.
LocalDateTime
Returns the converted DateTime, taking into account the offset (i.e., in the local time zone).
Offset
Returns the offset relative to UTC.
UtcDateTime
Returns a DateTime as UTC time.
The DateTime property returns you a DateTime (not cast to the local time zone), and the Offset property has the TimeSpan format, which represents the offset from UTC. There are also LocalDateTime and UtcDateTime properties that convert the given DateTimeOffset to DateTime for the local time zone or UTC.
I also note that the Now and UtcNow properties of the DateTimeOffset structure do not return the DateTime type, but DateTimeOffsets with the corresponding offset from UTC. Of course, like DateTime, DateTimeOffset has methods that deal with date / time, returning the DateTimeOffset type instead of DateTime.
So how does all this help us in the above example? Now we know that the third party sends us the date and time of its time zone, which does not need to be converted to a local date / time. Therefore, you can use DateTimeOffset.Parse () (or TryParse ()) and select only the date: Thus, you can easily parse dates without having to track the “midnight shift” or use it where you need to have a date, time and offset without conversion at local time. Results Although the DateTime structure is quite powerful in terms of parsing, manipulating and comparing dates / times, it can deliver a lot of unpleasant minutes in working with dates in the format of different time zones. DateTimeOffset in this case is much more flexible, since it uses an offset from UTC.
// ясно что здесь выполняется чтение файла/потока/и т.п.
var dateString = "2012-03-01 00:00:00-05:00";
// парсим день рождения как смещение даты/времени (без конвертирования в локальные даты/время)
var dtOffset = DateTimeOffset.Parse(dateString);
// теперь если нам надо сравнить результат с другими объектами типа локального DateTime
// мы просто используем свойство Date для получения даты
// без времени или смещения
var theDay = dtOffset.Date;Free translation (c) by V.F. Alien aka hDrummer, original here .