1110
1110

Reputation: 6829

How to get UTC for date in midnigs in swift

Can somebody help me to get current UTC date time.
I am trying:

let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let components = cal.components([.Day , .Month, .Year ], fromDate: NSDate())
        let refDate = cal.dateFromComponents(components)

But I am getting 1/12/2017 23:00:00 This is seems UTC local time.
I want to get UTC for current date at midnight.

In database I save date as number of seconds but on server it is saved as 1/13/2017 00:00:00 and in swift I am getting 1/12/2017 23:00:00 so I can't get values as they are different I don't understand what I need to do to get same UTC.

In database I save date as long number of seconds in swift I am getting it by UInt64(floor(refDate!.timeIntervalSince1970)) but date is incorrect.

Upvotes: 1

Views: 2231

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to set hour, minute and second property of NSDateComponents to 0

let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let components = cal.components([.Day , .Month, .Year,.Hour, .Minute, .Second], fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
let refDate = cal.dateFromComponents(components)

Or from iOS 8 you can also use startOfDayForDate

let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let refDate = cal.startOfDayForDate(NSDate())
print(refDate)

Upvotes: 3

Related Questions