将 UTC 日期格式转换为本地 nsdate [英] Converting UTC date format to local nsdate

查看:40
本文介绍了将 UTC 日期格式转换为本地 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.

我的代码:

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,日期:可选(2015-04-01 08:42:00 +0000)

utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 08:42:00 +0000)

我的本​​地时区是 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 = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        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 = NSTimeZone.local
        let timeStamp = dateFormatter.string(from: date!)

这篇关于将 UTC 日期格式转换为本地 nsdate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆