Conversion du format de date UTC en nsdate local
Je reçois de mon serveur une date de chaîne dans le fuseau horaire UTC et je dois la convertir en fuseau horaire local.
MON CODE:
let utcTime = "2015-04-01T11:42:00.269Z"
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString(utcTime)
println("utc: (utcTime), date: (date)")
Cela imprime -
Utc: 2015-04-01T11: 42: 00.269 Z, date: facultatif(2015-04-01 11:42:00 +0000)
Si je supprime
dateFormatter.timeZone = NSTimeZone(name: "UTC")
, Il imprime
Utc: 2015-04-01T11: 42: 00.269 Z, date: facultatif(2015-04-01 08:42:00 +0000)
Mon fuseau horaire local est UTC + 3 et dans la première option je reçois UTC dans la deuxième option je reçois UTC -3
Je devrais obtenir
Utc: 2015-04-01T11: 42: 00.269 Z, date: facultatif(2015-04-01 14:42:00 +0000)
Alors, comment convertir le format de date UTC en heure locale?
7 réponses
Quelque chose comme ce qui suit a fonctionné pour moi dans Objective-C:
// create dateFormatter with UTC time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string
// change to a readable time format and change to local time zone
[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];
Je garde ces deux sites à portée de main pour convertir différents formats de temps: http://www.w3.org/TR/NOTE-datetime
Http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
Dans Swift ce sera:
// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")// create date from string
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
Version Swift de c_rath réponse:
// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
Essayez cette extension Swift
Swift 4 : UTC / GMT Local Local (courant/Système)
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()
print("utcDate - (utcDate)")
print("localDate - (localDate)")
Dans Swift 3 cela fonctionne bien:
// create dateFormatter with UTC time format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create date from string
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date!)
En développant ce que d'autres ont mentionné, voici une extension pratique NSDate
dans Swift
import Foundation
extension NSDate {
func ToLocalStringWithFormat(dateFormat: String) -> String {
// change to a readable time format and change to local time zone
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(self)
return timeStamp
}
}
Peut-être que vous pouvez essayer quelque chose comme:
extension NSDate {
convenience init(utcDate:String, dateFormat:String="yyyy-MM-dd HH:mm:ss.SSS+00:00") {
// 2016-06-06 00:24:21.164493+00:00
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(utcDate)!
let s = NSTimeZone.localTimeZone().secondsFromGMTForDate(date)
let timeInterval = NSTimeInterval(s)
self.init(timeInterval: timeInterval, sinceDate:date)
}
}
J'ai dû supprimer les deux secondes z et milli de la solution c_rath. Fonctionne dans swift 4.
extension String {
func fromUTCToLocalDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
var formattedString = self.replacingOccurrences(of: "Z", with: "")
if let lowerBound = formattedString.range(of: ".")?.lowerBound {
formattedString = "\(formattedString[..<lowerBound])"
}
guard let date = dateFormatter.date(from: formattedString) else {
return self
}
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = TimeZone.current
return dateFormatter.string(from: date)
}
}