将UTC日期格式转换为本地nsdate [英] Converting UTC date format to local nsdate
问题描述
我从服务器获取UTC时区的字符串日期,我需要将其转换为本地时区。
I am getting from my server a string date in UTC time zone and I need to convert it to the local time zone.
MY 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)")
打印 -
utc:2015-04-01T11:42:00.269Z,日期:可选(2015-04-01 11:42:00 +0000)
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 11:42:00 +0000)
如果我删除
dateFormatter.timeZone = NSTimeZone(name: "UTC")
打印
utc:2015-04-01T11:42:00.269Z,date:Optional(2015-04-01 08:42:00 +0000)
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 08:42:00 +0000)
my local时区是UTC +3
,在第一个选项中我获得UTC
第二个选项我得到UTC -3
my local time zone is UTC +3 and in the first option I get UTC in the second option I get UTC -3
我应该
utc:2015-04-01T11:42:00.269Z,日期:可选(2015- 04-01 14:42:00 +0000)
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 14:42:00 +0000)
那么如何将UTC日期格式转换为当地时间?
So how do I convert the UTC date format to local time?
推荐答案
以下内容在Objective-C中为我工作:
Something along the following worked for me in 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];
我将这两个网站保留用于转换不同的时间格式:
http://www.w3.org/TR/NOTE-datetime
I keep these two websites handy for converting different time formats: http://www.w3.org/TR/NOTE-datetime
http:// benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
在Swift中它将是:
In Swift it will be:
// 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!)
这篇关于将UTC日期格式转换为本地nsdate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!