Understanding Date and DateComponents

Localizing_date_and_time.png (2960×1700)

Date is a specific point in time, independent of any calendar or time zone. Date values represent a time interval relative to an absolute reference date. You might come datetime calculator online  across this concept if you have ever work with Unix timestamp, which describes a date in the form of a time interval that has elapsed since the Unix epoch[1] (00:00:00 UTC on 1 January 1970).

Representing a date by a time interval makes it an easy task for the Date structure to provide methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.

Date in our daily life
I point out that a Date is independent of a calendar or time zone because it is a crucial difference from date and time as we know and use it in our daily life.

If you ask the question, “what day is today?” in your office, you might get the same answer regardless of who you ask. But if you ask the same question on the internet, you might get a different one. That’s because people in your office assume the same calendar and time zone as you, but the people on the internet think in their calendar and time zone. That’s why you might get a different answer to the very same question.

So the same date in code might not be the same date as we comprehend it. To create meaningful localized representations of dates and times, we need a calendar and timezone.

In iOS, we have many classes that do the hard lifting, such as DateFormatter that converts between dates and their textual representations.

But the above example didn’t take time zone and calendar into account, so the result might not be the one we expected since not every month has 30 days, and in some areas, there is a daylight saving concept, which means some days might be more or less than 24 hours. That’s why we have DateComponents.

As you can see, just a unit of time is not sufficient to pinpoint a specific point in time. Because when we say January 1, 2020, we leave out two hidden components. That is a time zone and calendar. If you open a television on a new year’s day, you would see that the firework doesn’t happen at the same time. Because we interpret a new years’ day in our own time zone.

So, let’s look back at our question. We leave out calendar and timezone as nil here. So, the system use calendar and timezone of the receiver instead let date = Calendar.current.date(from: comps)!. In this case, it is the current calendar and time zone, Calendar.current.

Conclusion
It is a lot easier to manipulate date and time with DateComponents because it aligns with how we interpret date and time in the real world. That’s why you will see a lot of Calendar methods involve


Comments

Leave a comment

Design a site like this with WordPress.com
Get started