创建具有特定时区的NSDate对象 [英] Creating NSDate object with specific time zone

查看:208
本文介绍了创建具有特定时区的NSDate对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个接受NSDate对象的方法,并将其转换为具有EST时区的NSDate对象.我见过其他人完成此操作的方式是使用日期格式化程序将日期更改为具有指定时区的字符串.问题是当我尝试使用"dateFromString"将该字符串更改回NSDate对象时.

I've written a method that accepts a NSDate object and should turn it into a NSDate object with EST time zone. The way I've seen other people accomplish this is by using a date formatter to change the date to a string with the specified time zone. The issue is when I try to change that string back to a NSDate object using "dateFromString".

- (NSDate*)turnToEST:(NSDate*)date
{
NSLog(@"turnToEST called with date %@", date);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"EST"]];

NSString *stringFromDate = [dateFormatter stringFromDate:date];

NSLog(@"date formatted is %@", stringFromDate);

NSDate *dateFromString = [[NSDate alloc] init];

NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
[dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

dateFromString = [dateFormatter2 dateFromString:stringFromDate];

NSLog(@"date has been changed to %@", dateFromString);

return date;
}

有输出...

turnToEST called with date 2013-12-19 14:15:17 +0000
date formatted is 2013-12-19 09:15:17
date has been changed to 2013-12-19 14:15:17 +0000

我不确定为什么这与

将NSString转换为NSDate(并再次返回)

推荐答案

NSDate没有具有关联的时区,它们表示抽象的时间点.因此,具有EST时区的NSDate对象"不存在.仅在格式化时区以进行输出或尝试进行基于日历的数学时,时区才会发挥作用.

NSDate values do not have an associated time zone, they represent an abstract moment in time. So "a NSDate object with EST time zone" isn't a thing that exists. Time zones only come into play when formatting them for output, or trying to do calendar-based math.

NSLog在打印输出时始终使用UTC.

NSLog always uses UTC when printing its output.

因此,您需要花费一些时间,将其格式化为特定时区的字符串,然后将其解析回同一时间.可以按预期工作.

So you're taking a moment in time, formatting it to a string in a particular time zone, and then parsing it back into the same moment in time. That's working as intended.

这篇关于创建具有特定时区的NSDate对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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