---恢复内容开始---

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;
    
}

iOS Developer Library Developer

Search

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// Returns a user-visible date time string that corresponds to the // specified RFC 3339 date time string. Note that this does not handle // all possible RFC 3339 date time strings, just one of the most common // styles.
{NSString *          userVisibleDateTimeString;NSDateFormatter *   rfc3339DateFormatter;NSLocale *          enUSPOSIXLocale;NSDate *            date;NSDateFormatter *   userVisibleDateFormatter;userVisibleDateTimeString = nil;// Convert the RFC 3339 date time string to an NSDate.rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease];assert(rfc3339DateFormatter != nil);enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];assert(enUSPOSIXLocale != nil);[rfc3339DateFormatter setLocale:enUSPOSIXLocale];[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];if (date != nil) {// Convert the NSDate to a user-visible date string.userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease];assert(userVisibleDateFormatter != nil);[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];}return userVisibleDateTimeString;
}

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// Returns a user-visible date time string that corresponds to the // specified RFC 3339 date time string. Note that this does not handle // all possible RFC 3339 date time strings, just one of the most common // styles.
{static NSDateFormatter *    sRFC3339DateFormatter;NSString *                  userVisibleDateTimeString;NSDate *                    date;// If the date formatters aren't already set up, do that now and cache them // for subsequence reuse.if (sRFC3339DateFormatter == nil) {NSLocale *                  enUSPOSIXLocale;sRFC3339DateFormatter = [[NSDateFormatter alloc] init];assert(sRFC3339DateFormatter != nil);enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];assert(enUSPOSIXLocale != nil);[sRFC3339DateFormatter setLocale:enUSPOSIXLocale];[sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];[sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];}if (sUserVisibleDateFormatter == nil) {sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];assert(sUserVisibleDateFormatter != nil);[sUserVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];[sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];}// Convert the RFC 3339 date time string to an NSDate.// Then convert the NSDate to a user-visible date string.userVisibleDateTimeString = nil;date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];if (date != nil) {userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];}return userVisibleDateTimeString;
}

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 explains how to use NSDateFormatter with fixed-format dates, like those in various Internet protocols.


Copyright © 2010 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2010-04-29

Provide Feedback

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.

---恢复内容结束---

转载于:https://www.cnblogs.com/lisa090818/p/3483768.html

时间和字符串的相互转换相关推荐

  1. 日期时间格式之间的相互转换

    import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; impo ...

  2. python时间日期字符串各种

    python时间日期字符串各种 python时间日期字符串各种 第一种 字符串转换成各种日期 time 库 # -*- coding: utf-8 -*- import time, datetime ...

  3. .NET(C#)时间日期字符串(String)格式化转换成Datetime异常报错问题

    .NET(C#)时间日期字符串(String)格式化转换成Datetime异常报错问题 参考文章: (1).NET(C#)时间日期字符串(String)格式化转换成Datetime异常报错问题 (2) ...

  4. 整型(int)转时间格式字符串及页面long型转时间格式字符串

    1,如果是封装的整型的话需要在后台进行处理再返回页面 处理过程是这样的 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm ...

  5. php中如何比较数组和字符串,PHP中数组和字符串的相互转换-PHP数组和字符串互相转换方法-吾爱编程网...

    网站开发过程中有时候会有一些字符串和数组互转,接下来吾爱编程为大家介绍一下字符串和数组互转的方法,有需要的小伙伴可以参考一下: 1.将字符串转换为数组:/** * 将字符串转换为数组 * @param ...

  6. C语言如何返回格式化日期时间(格式化时间)?(将日期和时间以字符串格式输出)ctime()、asctime()、localtime()、strftime()

    文章目录 ctime()函数: asctime()函数 获取自定义格式化时间(有bug,当时间为个位数时,没有在前面自动补零) 改成函数接口形式(传入字符指针) 20220107 优化后(能自动补零) ...

  7. 把一个中文日期时间格式字符串转为日期时间

    MS SQL Server2012中把一个中文日期时间格式字符串转为日期时间. 如: DECLARE @d NVARCHAR(20) = N'2012年08月12日14时36分48秒' SELECT  ...

  8. mysql时间与字符串相互转换

    转载自 https://www.cnblogs.com/wangyongwen/p/6265126.html 时间.字符串.时间戳之间的互相转换很常用,但是几乎每次使用时候都喜欢去搜索一下用法:本文整 ...

  9. 【转载保存】MySQL时间、字符串、时间戳互相转换

    时间转字符串 select date_format(now(), '%Y-%m-%d %H:%i:%s');  结果:2018-05-02 20:24:10 时间转时间戳 select unix_ti ...

最新文章

  1. c# winform编程之多线程ui界面资源修改总结篇
  2. AWS — AWS ECS
  3. 更改日期为英文_如何在 Linux 上检查所有用户密码到期日期 | Linux 中国
  4. 【视频课】零基础免费38课时深度学习+超60小时CV核心算法+15大Pytorch CV实践案例助你攻略CV...
  5. why my employee binding does not work - important MVC debug
  6. Keras-保存和恢复模型
  7. matlab下pid控制仿真,利用Matlab实现PID控制仿真
  8. mysql 不认的字符串_mysql 判断字符串是否为其他字符串的子集
  9. 一款 SQL 自动检查神器!
  10. MacBook Pro下载工具
  11. screentogif能录制声音吗_一款免费且强大的gif动画录制工具,再也不愁录动画!...
  12. shell脚本之循环语句
  13. Linux下MinDoc安装使用
  14. ps 改变图片中的文字
  15. 假设检验之几种检验方法的比较
  16. [book]《巅峰表现》
  17. 哈尔滨工业大学邮件系统客户端设置
  18. [易飞]关于自制件调整为虚设件的处理方案
  19. 关于小学生学习编程语言C++的经历经验分享,五问五答
  20. Repeater的 Items属性、Items里面的控件有几个?

热门文章

  1. 大数据精准营销:如何找对人做对事?
  2. 两种计算Java对象大小的方法
  3. HasValue 判断可空类型是否有值
  4. springboot 集成Quartz实现任务延迟执行和定时执行功能
  5. 周立波最新经典语录--天空16度蓝
  6. .net core 登入全局验证过滤器
  7. 制作一个答题系统,随机出现二十道题.
  8. Oracle的基本操作
  9. DataX使用指南——ODPS to ODPS
  10. 小时候计算机课玩的那个兔子的游戏是什么,童年小确幸 儿时电脑课里我们玩不腻的13个小游戏...