4

I am trying to get date components from a date value from an API endpoint. I need to preserve the date values as they are already adjusted for time zone. Unfortunately, I have no control over how the API returns a date value.

When I get the date value (sessionTime) from the API, it is returned as follows:

2017-12-05 08:00:00 +0000

I need to set up a local notification based on that time, however, when I try to extract components from that date object with the following code:

let notifyTime = Calendar.current.dateComponents(
     [.year, .month, .day, .hour, .minute, .second], from: sessionTime)

I get this:

year: 2017 month: 12 day: 5 hour: 2 minute: 0 second: 0 isLeapMonth: false 

I am six hours from GMT so it is obvious what is going on, but I wish I could prevent it and extract the date components exactly as they are. The desired output would be:

year: 2017 month: 12 day: 5 hour: 8 minute: 0 second: 0 isLeapMonth: false

Can anyone help? Thanks!

Pheepster
  • 6,045
  • 6
  • 41
  • 75

1 Answers1

6

You can specify the timeZone that DateComponents uses.

Like this:

let notifyTime = Calendar.current.dateComponents(in: TimeZone.current, from: sessionTime)
85Camaro
  • 503
  • 4
  • 7