iOS NSDateFormatter 时区 [英] iOS NSDateFormatter Timezone

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

问题描述

我有一些代码接受一个字符串,把它变成一个日期,重新格式化然后把它作为另一个字符串吐出来:

I have some code that takes a string, turns it into a date, reformats it then spits it out as another string:

[formatter setDateFormat:@"YYYY'-'MM'-'DD','HH:mm:ss','ZZZ"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate *date = [formatter dateFromString:combinedString];
[formatter setDateStyle:NSDateFormatterLongStyle];
NSString *finishedString = [formatter stringFromDate:date];

基本上,除了时区之外,它工作正常.所有输入字符串都在时区 -0400 中,我希望重新格式化的字符串也位于该时区,但重新格式化的字符串继续向前转换 4 小时,即使我添加了 setTimeZone: 行.基本上,我根本不想改变时间,我只想重新格式化它,我不明白我做错了什么?

Basically, it works fine except for the timezones. All of the input strings are in timezone -0400, and I want the reformatted string to be in that timezone also, but the reformatted string keeps being converted forward 4 hours, even after I added the setTimeZone: line. Basically, I don't want to change the time at all, I just want to reformat it, and I can't understand what I am doing wrong?

推荐答案

这取决于日期来源中指定的格式.大多数时候我处理 Unix/POSIX 格式的日期.然后我用下面两行代码:

It depends on format specified on the source of your dates. Most of the times I deal with dates in Unix/POSIX format. Then I use the following two lines of code:

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

无论如何,我建议您查看 Apple Developers 网站上的以下问答:http://developer.apple.com/library/ios/#qa/qa1480/_index.html

Anyway, I recommend you to check the following Q&A from Apple Developers site: http://developer.apple.com/library/ios/#qa/qa1480/_index.html

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

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