-3

Does anyone knows how to print the time at the end of the Location? when printing out the full location in the following code:

There is a time difference between the time in the result while printing out the Location and the time location?.timestamp Optional:

geofire?.setLocation(location, forKey: uid) { (error) in
            if (error != nil) {
                print("An error occured: \(error)")
            } else {
                print(location)

RESULT: Optional(<+xx.xxxxxx,+xx.xxxxxxxx> +/- 5.00m (speed 0.00 mps / course -1.00) @ 21/11/2016, 16:04:32 Central European Standard Time)

and by printing out only:

print(location?.timestamp)

RESULT:Optional(2016-11-21 15:04:32 +0000)

How to print only "16:04:32 Central European Standard Time" or even with the date before "21/11/2016, 16:04:32 Central European Standard Time" ? Thanks

adjuremods
  • 2,938
  • 2
  • 12
  • 17
Gael
  • 1
  • 4
  • Possible duplicate of [Swift - IOS - Dates and times in different format](http://stackoverflow.com/questions/28489227/swift-ios-dates-and-times-in-different-format) – xoudini Dec 20 '16 at 22:04

1 Answers1

0

The timestamp in a CLLocation is simply a Date variable. You're getting different results when printing the location and the timestamp because they're translated into two different timezones.

A Date timestamp represents an abstract moment in time and has no calendar system or a particular timezone. CLLocation's description on the other hand converts that time to your local timezone for better clarification. They're both equivalent; one (the timestamp) shows 15:04:32 GMT, the other shows 16:04:32 Central European Standard Time, which is +1 GMT without DST.

To get your local time from the timestamp, you can reformat the Date object like this

    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm:ss"   // use "dd/MM/yyyy, HH:mm:ss" if you want the date included not just the time
    formatter.timeZone = NSTimeZone.local
    let timestampFormattedStr = formatter.string(from: (location?.timestamp)!)  // result: "16:04:32"

    // get timezone name (Central European Standard Time in this case)
    let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
    let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)!
    let timestampWithTimeZone = "\(timestampFormattedStr!) \(timeZoneName)" // results: "16:04:32 Central European Standard Time"

If local time is crucial to your implementation, I would suggest checking for DST as well. You can check like this

if timeZone.isDaylightSavingTimeForDate((location?.timestamp)!) {

}
ThunderStruct
  • 1,504
  • 6
  • 23
  • 32