Skip to content

Instantly share code, notes, and snippets.

@MattCheetham
Last active March 7, 2017 12:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattCheetham/c717648e9604d19615d7ee89dbc695aa to your computer and use it in GitHub Desktop.
Save MattCheetham/c717648e9604d19615d7ee89dbc695aa to your computer and use it in GitHub Desktop.
Swift date formatting
//: Playground - noun: a place where people can play
import UIKit
/// We're working with appointments.
/// So I get this string from the server and in some places I need to display it in the users local timezone and in other places I need to display it as the time and date that it was booked
var serverTimeString = "2017-03-21T19:00:00-07:00"
let localisedDateFormatter = DateFormatter()
localisedDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
// Displays as March 22nd, 2am (GMT) - CORRECT
var date = localisedDateFormatter.date(from: serverTimeString)
// TO DO: Output date as March 21st, 7pm.
// ??
@tmdvs
Copy link

tmdvs commented Mar 7, 2017

@MattCheetham

This works, I get Tuesday, 21 March 2017 at 19:00:00 GMT-07:00

do {
            let serverTimeString = "2017-03-21T19:00:00-07:00"
            let pattern = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}([\\d:\\-].*)"
            
            let rexp = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
            let matches = rexp.matches(in: serverTimeString, options: [], range: NSMakeRange(0,25))
            
            let timezone = (serverTimeString as NSString).substring(with: matches.last!.rangeAt(1)) as NSString
            let tzParts = timezone.components(separatedBy: ":")
            let hours = tzParts[0] as NSString
            let minutes = tzParts[1] as NSString
            
            let secondsSinceGMT = (hours.integerValue * 60 * 60) + (minutes.integerValue * 60)
            print(secondsSinceGMT)
            
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
            formatter.timeZone = TimeZone(secondsFromGMT: secondsSinceGMT)
            
            let date = formatter.date(from: serverTimeString)
            
            let displayFormatter = DateFormatter()
            displayFormatter.dateStyle = .full
            displayFormatter.timeStyle = .full
            displayFormatter.timeZone = TimeZone(secondsFromGMT: secondsSinceGMT)
            
            print(displayFormatter.string(from: date!))
            
        } catch {
            // something borked
        }

@tmdvs
Copy link

tmdvs commented Mar 7, 2017

Could likely tidy it up. I've used regex and timezone calculations to try and catch any timezone not just -7 hours

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment