0

It's generaly accepted as a good practise to store dates as UTC/GMT and convert them back to local time when they need to be displayed to the user. Working currently on calendar app I am wondering how to do this for future/past dates taking into account the current Daylight saving time.

Date to UTC:

 let date = Date()  
 let dateFormatter = DateFormatter()
 dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
 let dt = dateFormatter.date(from: date)

Date back to local time:

 let date = Date()  
 let dateFormatter = DateFormatter()
 dateFormatter.timeZone = TimeZone.current
 let dt = dateFormatter.date(from: date)

Example: When a user living in Amsterdam schedules a future meeting from 4pm to 5pm (UTC+2). I'll be storing the UTC equivalent which is 2pm to 3pm. Now if he would like check his meeting in two months when Amsterdam has passed from summer- to winter-time (UTC-1), the user will see that his meeting has shifted to 3pm - 4pm.

How would I best tackle this ?

Oysio
  • 3,486
  • 6
  • 45
  • 54
  • 1
    No that would not happen. If you convert (say) "2019-12-12 16:00" from Amsterdam time to UTC then you'll get "2019-12-12 15:00", no matter whether DST is *currently* active or not. – Martin R Oct 25 '19 at 12:38
  • Can you provide a [mcve]? – Sweeper Oct 25 '19 at 13:43
  • Well I guess the real question is how do you account for Daylight saving time when you store dates as UTC? Or does this work out somehow automatically by itself when you convert back to local time? – Oysio Oct 25 '19 at 13:57
  • A date is just a point in time. Don't worry about DST. If you need to display the date to the user just use DateFormatter. Note that there is no guarantee Amsterdam will always have daylight savings time. Brazil has just abolished it. – Leo Dabus Oct 25 '19 at 16:47
  • @LeoDabus can you please elaborate with an answer? So using DateFormatter with current Locale will decide to apply DST and will output the original recorded time, even if the DST rules had changed in the meantime? Confuses me how DateFormatter would know what DST rules to apply for a particular locale at a given time in the future. – Oysio Oct 25 '19 at 21:24
  • 1
    yes Apple releases timezone device updates if needed. All you need is to parse your date string properly respecting the timezone if included in your string or using a specific one (like a server timezone or utc timezone). The date is just a moment in time. When displaying it to the user you just need to use date formatter to display the time localized at current timezone – Leo Dabus Oct 25 '19 at 21:38
  • https://stackoverflow.com/a/28347285/2303865 – Leo Dabus Oct 25 '19 at 21:39

0 Answers0