ios下读取jason中的nsstring时间并本地化成中文gmt时间显示上午下午
https://developer.apple.com/library/ios/qa/qa1480/_index.html
- (NSDate *)dateFromString:(NSString *)string {
if (!string) {
return nil;
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat : @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'"];
[formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] autorelease]];
NSTimeZone *pdt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[formatter setTimeZone:pdt];
NSDate *dateTime = [formatter dateFromString:string];
[formatter release];
NSLog(@"%@", dateTime);
return dateTime;
}
- (NSString *)stringFromDate:(NSDate *)date{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] autorelease]];
NSTimeZone *pdt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:pdt];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *destDateString = [dateFormatter stringFromDate:date];
[dateFormatter release];
return destDateString;
}
NSDateFormatter and Internet Dates
NSDateFormatter and Internet Dates
Q: I'm using NSDateFormatter to parse an Internet-style date, but this fails for some users in some regions. I've set a specific date format string; shouldn't that force NSDateFormatter to work independently of the user's region settings?
A: I'm using NSDateFormatter to parse an Internet-style date, but this fails for some users in some regions. I've set a specific date format string; shouldn't that force NSDateFormatter to work independently of the user's region settings?
No. While setting a date format string will appear to work for most users, it's not the right solution to this problem. There are many places where format strings behave in unexpected ways. For example:
On Mac OS X, a user can change their calendar (using System Preferences > Language & Text > Format > Calendar). In that case NSDateFormatter will treat the numbers in the string you parse as if they were in the user's chosen calendar. For example, if the user selects the Buddhist calendar, parsing the year "2010" will yield an NSDate in 1467, because the year 2010 on the Buddhist calendar was the year 1467 on the (Gregorian) calendar that we use day-to-day.
On iPhone OS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set, which can cause your time parsing to fail.
To solve this problem properly, you have to understand that NSDateFormatter has two common roles:
generating and parsing user-visible dates
generating and parsing fixed-format dates, such as the RFC 3339-style dates used by many Internet protocols
If you're working with user-visible dates, you should avoid setting a date format string because it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:]
and -[NSDateFormatter setTimeStyle:]
).
On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iPhone OS as it does on Mac OS X, and as it it does on other platforms).
Once you've set "en_US_POSIX" as the locale of the date formatter, you can then set the date format string and the date formatter will behave consistently for all users.
Listing 1 shows how to use NSDateFormatter for both of the roles described above. First it creates a "en_US_POSIX" date formatter to parse the incoming RFC 3339 date string, using a fixed date format string and UTC as the time zone. Next, it creates a standard date formatter for rendering the date as a string to display to the user.
Listing 1 Parsing an RFC 3339 date-time
- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString |
The code in Listing 1 is correct, but it's not as efficient as it could be. Specifically, it creates a date formatter, uses it once, and then throws it away. A better approach is the one shown in Listing 2. This holds on to its date formatters for subsequent reuse.
Listing 2 Parsing an RFC 3339 date-time more efficiently
static NSDateFormatter * sUserVisibleDateFormatter; - (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString |
If you cache date formatters, or any other objects that depend on the user's current locale, you should subscribe to the NSCurrentLocaleDidChangeNotification
notification and update your cached objects when the current locale changes. The code in Listing 2 defines sUserVisibleDateFormatter
outside of the method so that other code, not shown, can update it as necessary. In contrast, sRFC3339DateFormatter
is defined inside the method because, by design, it is not dependent on the user's locale settings.
Warning: In theory you could use +[NSLocale autoupdatingCurrentLocale]
to create a locale that automatically accounts for changes in the user's locale settings. In practice this currently does not work with date formatters (r. 7792724) .
Finally, if you're willing to look at solutions outside of the Cocoa space, it's very easy and efficient to parse and generate fixed-format dates using the standard C library functions strptime_l
and strftime_l
. Be aware that the C library also has the idea of a current locale. To guarantee a fixed date format, you should pass NULL
to the loc
parameter of these routines. This causes them to use the POSIX locale (also known as the C locale), which is equivalent to Cocoa's "en_US_POSIX" locale.
Document Revision History
Date | Notes |
---|---|
2010-04-29 |
RFC 3339 dates are always in UTC, so set the time zone on the RFC 3339 date formatter to UTC. |
2010-03-31 |
New document that |
Copyright © 2010 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2010-04-29
How helpful is this document?
*
Very helpful
Somewhat helpful
Not helpful
How can we improve this document?
Fix typos or links
Fix incorrect information
Add or update code samples
Add or update illustrations
Add information about...
*
* Required information
To submit a product bug or enhancement request, please visit the Bug Reporter page.
Please read Apple's Unsolicited Idea Submission Policy before you send us your feedback.
ios下读取jason中的nsstring时间并本地化成中文gmt时间显示上午下午的更多相关文章
- iOS下Html页面中input获取焦点弹出键盘时挡住input解决方案—scrollIntoView()
问题描述 iOS系统下,移动web页面,inpu获取焦点弹出系统虚拟键盘时,偶尔会出现挡住input的情况,尽管概率不大,但是十分影响用户体验. 问题重现 原始页面:页面中有header.main.f ...
- iOS下Html页面中input获取焦点弹出键盘时挡住input解决方案
问题描述 iOS系统下,移动web页面,inpu获取焦点弹出系统虚拟键盘时,偶尔会出现挡住input的情况,尽管概率不大,但是十分影响用户体验. 问题重现 原始页面:页面中有header.main.f ...
- js下读取input中的value值
很多人(包括我),总想像以前操作js一样,读取到input中的值:document.getElementById('').value; 结果事实证明这样读到得是null. eval(document. ...
- 踩坑事件:windows操作系统下的eclipse中编写SparkSQL不能从本地读取或者保存parquet文件
这个大坑... .... 如题,在Windows的eclipse中编写SparkSQL代码时,编写如下代码时,一运行就抛出一堆空指针异常: // 首先还是创建SparkConf SparkConf c ...
- Xshell终端连接CentOS7.0下Docker容器中的MySql镜像后无法键入中文问题
首先在宿主机输入env 查看LANG 或者 locale 查看 LANG 发现本地使用的字符集是: zh_CN.UTF-8 然后执行 docker exec -it mysql bash 进入dock ...
- js动态获取当前时间(年、月、日、上午/下午、时、分、秒)
//获取动态时间function mytime() { var mydate = new Date(); var year = mydate.getFullYear(); var month = my ...
- ios下点击穿透focus获取问题
在ios下的浏览器中当点击当前页的一个按钮,用window.location.href进行跳转时,如果下一个页面里这点击按钮的位置是一个textarea或者text等那么他会触发focus事件,会出现 ...
- python 1: 解决linux系统下python中的matplotlib模块内的pyplot输出图片不能显示中文的问题
问题: 我在ubuntu14.04下用python中的matplotlib模块内的pyplot输出图片不能显示中文,怎么解决呢? 解决: 1.指定默认编码为UTF-8: 在python代码开头加入如下 ...
- CST和GMT时间的区别
CST和GMT时间的区别 今天遇到一个奇怪的问题,在服务器端通过 c# 获取当前时间为 Fri Aug 28 09:37:46 CST 2009, 转化为 GMT时间为:28 Aug 2009 01: ...
随机推荐
- 条款39:明智而审慎地使用private继承(use private inheritance judiciously)
NOTE: 1.private 继承意味 is-implemented-in-terms-of(根据某物实现出).它通常比复合(composition)的级别低.但是当derivated class需 ...
- python--类的约束, 异常处理, MD5, 日志处理
一 . 类的约束 1. 写一个父类,父类中的某个方法要抛出一个异常 NotImplementedError class Base: # 对子类进行了约束. 必须重写该方法 # 以后上班了. 拿到公司代 ...
- python爬虫入门四:BeautifulSoup库(转)
正则表达式可以从html代码中提取我们想要的数据信息,它比较繁琐复杂,编写的时候效率不高,但我们又最好是能够学会使用正则表达式. 我在网络上发现了一篇关于写得很好的教程,如果需要使用正则表达式的话,参 ...
- 不同深度的图片转换cvConvertScale
不同深度图像的转换:要注意范围比如IPL_DEPTH_8U 转到 IPL_DEPTH_32U要用cvConvertScale(pImg8, pImg32, 1.0/255, 0); 要除255反过来I ...
- Python第三方库之openpyxl(4)
Python第三方库之openpyxl(4) 2D柱状图 在柱状图中,值被绘制成水平条或竖列. 垂直.水平和堆叠柱状图. 注意:以下设置影响不同的图表类型 1.在垂直和水平条形图之间切换,分别设置为c ...
- x86保护模式-七中断和异常
x86保护模式-七中断和异常 386相比较之前的cpu 增强了中断处理能力 并且引入了 异常概念 一 80386的中断和异常 为了支持多任务和虚拟存储器等功能,386把外部中断称为中断 ...
- EasyUI 动态更新列
function UpdateRow() { var rows = $('#tbpmgridList').datagrid('getChecked'); var productid = ''; for ...
- 【Luogu】P1005矩阵取数游戏(高精度+DP)
题目链接 yeah终于过辣! DP,f[i][j]表示每行还剩i到j这个区间的数没取的时候的值.借这个题我也把高精度的短板弥补了一下,以后高精加高精乘应该是没问题了. 哇终于不怂高精了…… 放上代码. ...
- POJ 2888 Magic Bracelet ——Burnside引理
[题目分析] 同样是Burnside引理.但是有几种颜色是不能放在一起的. 所以DP就好了. 然后T掉 所以矩阵乘法就好了. 然后T掉 所以取模取的少一些,矩阵乘法里的取模尤其要注意,就可以了. A掉 ...
- [BZOJ3545] [ONTAK2010]Peaks(线段树合并 + 离散化)
传送门 由于困难值小于等于x这个很恶心,可以离线处理,将边权,和询问时的x排序. 每到一个询问的时候,将边权小于等于x的都合并起来再询问. .. 有重复元素的线段树合并的时间复杂度是nlog^2n # ...