Date Formatters

来源:互联网 发布:数据质量检测报告 编辑:程序博客网 时间:2024/06/06 09:47

Date Formatters

    有两种基本方法,用来从一个字符串中创建一个 date 对象和从一个 date 对象中解析成一个字符串,dateFromString: and stringFromDate:,如果你需要对解析的字符串进行更多的控制,可以使用 getObjectValue:forString:range:error:方法,

    你可以通过直接使用 NSDateFormatter 来实现一些简单的时间显示,也可以通过指定字符串格式来解析你想要的时间格式,不管你使用哪一种方法,都应该考虑到用户的当前时区 (currentLocale),如果你想只获取用户的时区,不想要知道其他设置,可以通过直接获取(localeIdentifier),然后通过获取到的时区创建一个标准的NSLocale对象,并且赋值给 NSDateFormatter 的locale 对象。


Use Formatter Styles to Present Dates and Times With the User’s Preferences

   
     NSDateFormatter 包含五种常用格式,NSDateFormatterNoStyleNSDateFormatterShortStyleNSDateFormatterMediumStyleNSDateFormatterLongStyle, and NSDateFormatterFullStyle,示例1表明如何通过设置 dateStyle 和 timeStyle 来格式化 date 字符串
Listing 1 Formatting a date using formatter styles
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateStyle:NSDateFormatterMediumStyle];[dateFormatter setTimeStyle:NSDateFormatterNoStyle];NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];NSString *formattedDateString = [dateFormatter stringFromDate:date];NSLog(@"formattedDateString: %@", formattedDateString);// Output for locale en_US: "formattedDateString: Jan 2, 2001".


Use Format Strings to Specify Custom Formats
   
     在两种情况下你会需要自定义字符串格式,
  • For fixed format strings, like Internet dates.
  • For user-visible elements that don’t match any of the existing styles

Fixed Formats

    可以通过使用setDateFormat:方法来设置自定义的格式,这些格式需要遵循 the Unicode Technical Standard #35

    使用自定义字符串格式时,还需要考虑两件事情

  • NSDateFormatter treats the numbers in a 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 yields an NSDate object in 1467 in the Gregorian calendar. (For more about different calendrical systems and how to use them, see Date and Time Programming Guide.)
  • In iOS, the user can override the default AM/PM versus 24-hour time setting. This may cause NSDateFormatter to rewrite the format string you set.

    下面是如何使用自定义字符串格式的示例:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];NSString *formattedDateString = [dateFormatter stringFromDate:date];NSLog(@"formattedDateString: %@", formattedDateString);// For US English, the output may be:// formattedDateString: 2001-01-02 at 13:00

    There are two things to note about this example:

  • It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.
  • The representation of the time may be 13:00. In iOS, however, if the user has switched 24-Hour Time to Off, the time may be 1:00 pm.


Custom Formats for User-Visible Dates
     如果需要根据指定的一系列元素来格式化时间,你可以使用dateFormatFromTemplate:options:locale:函数,它用来根据用户所在地区和提供的元素生成一个对应的时间格式,下面这个示例演示了如何使用该函数,
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM" options:0                                          locale:[NSLocale currentLocale]];NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:formatString];NSString *todayString = [dateFormatter stringFromDate:[NSDate date]];NSLog(@"todayString: %@", todayString);

什么情况下你会需要使用这种方式呢?假设你现在需要显示某个时间的名称,日,和月,你是没办法使用自定义的格式来实现这个功能的,

  • 因为没有能够忽略年的自定义格式,
  • 因为无法统一的对不同地区使用相同的格式,例如,上述代码,在美国显示结果是EEE, MMM d,在德国是EEE d MMM.


Parsing Date Strings
- (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.     */    NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    // Convert the RFC 3339 date time string to an NSDate.    NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];    NSString *userVisibleDateTimeString;    if (date != nil) {        // Convert the date object to a user-visible date string.        NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];        assert(userVisibleDateFormatter != nil);        [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];        [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];        userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];    }    return userVisibleDateTimeString;}

Cache Formatters for Efficiency
     Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.

创建一个时间格式开销很大,如果需要频繁使用格式化,更有效的办法是创建一个单例,

下面是一个示例代码

static NSDateFormatter *sUserVisibleDateFormatter = nil;- (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.     */    // If the date formatters aren't already set up, create them and cache them for reuse.    static NSDateFormatter *sRFC3339DateFormatter = nil;    if (sRFC3339DateFormatter == nil) {        sRFC3339DateFormatter = [[NSDateFormatter alloc] init];        NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];        [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];        [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];        [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    }    // Convert the RFC 3339 date time string to an NSDate.    NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];    NSString *userVisibleDateTimeString;    if (date != nil) {        if (sUserVisibleDateFormatter == nil) {            sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];            [sUserVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];            [sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];        }        // Convert the date object to a user-visible date string.        userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];    }    return userVisibleDateTimeString;}  

你的时间格式应该响应用户地区变化,通过监听NSCurrentLocaleDidChangeNotification可以实现这点,



Consider Unix Functions for Fixed-Format, Unlocalized Dates
     如果你不需要关心时区,比如你的程序始终使用同一个日历,并且不会变化,那么你可以采用标准的 C 接口 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 as 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

示例代码:

struct tm  sometime;const char *formatString = "%Y-%m-%d %H:%M:%S %z";(void) strptime_l("2005-07-01 12:00:00 -0700", formatString, &sometime, NULL);NSLog(@"NSDate is %@", [NSDate dateWithTimeIntervalSince1970: mktime(&sometime)]);// Output: NSDate is 2005-07-01 12:00:00 -0700
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 快递柜单号没了怎么办 邮政蜜蜂箱 退件怎么办 手机狂收验证码怎么办 快递柜超过24小时怎么办 快递柜短信删了怎么办 丰巢电话留错了怎么办 e栈快递员软件打不开怎么办 耳朵里进了东西怎么办 e栈收不到取件码怎么办 挖机排放不达标怎么办 三星手机一直开机关机怎么办 高速路上胎爆了怎么办 迪兰588温度高怎么办 象印保温杯掉漆怎么办 报销的车票丢了怎么办 快递写错一个字怎么办 外国人在中国护照过期怎么办 大学选课选漏了怎么办 高德地图不能琦跨城导航怎么办 水痘预防针间隔时间太久怎么办 车载导航被删了怎么办 高德地图gps信号弱怎么办 ai里面图片太多文件太大怎么办 ai文件太大怎么办1个G 文件写错了字怎么办 戒指弄不下来了怎么办 高德地图反应慢怎么办 白色印花t恤染色怎么办 印花t恤图案掉了怎么办 衣服上印花掉了怎么办 ps cs 3图标太小怎么办 ai cs6图标太小怎么办 su界面太小怎么办win10 华为p9手机gps信号弱怎么办 小米手机导航gps信号弱怎么办 安卓手机gps信号弱怎么办 苹果6导航gps信号弱怎么办 苹果6plus反应慢怎么办 手机文件打开是乱码怎么办 手机wps文件打开是乱码怎么办 腾讯视频vip账号被盗怎么办