iOS时间处理(NSDate、NSDateComponents、NSCalendar、NSDateFormatter、NSTimeZone)

1.NSDate存储的是世界标准时(UTC),输出时需要根据时区转换为本地时间

2.NSTimeInterval: 时间戳,以double为单位

3.系统返回的时间都是格林尼治时间,要得到北京时间需要转化

 


 

NSDate类:
 
@interface NSDate (NSDateCreation)中方法:创建或初始化NSDate值
NSDate返回日期
 
@interface NSDate (NSExtendedDate): NSDate的扩张方法
方法一:日前之间的前后比较
方法二:得到距离某一日起的时间间隔(时间戳)
方法三:得到在当前实例中保存的时间为基准, 过了sec的日期
方法四:将时间表示字符串:description  其实这个方法写不写一样 系统会自动的
 
参考:
冷雨之家博客对该类方法作了详尽的描述:http://hi.baidu.com/douxinchun/item/86c9732bc603349db73263ae

 


NSDateComponents类:()
 
NSDateComponents封装在一个可扩展的,面向对象的方式的日期组件。它是用来弥补时间的日期和时间组件提供一个指定日期:小时,分钟,秒,日,月,年,等等。它也可以用来指定的时间,例如,5小时16分钟。一个NSDateComponents对象不需要定义所有组件领域。当一个NSDateComponents的新实例被创建,日期组件被设置为NSUndefinedDateComponent。
一个NSDateComponents对象本身是毫无意义的;你需要知道它是针对什么日历解释,你需要知道它的值是否是正整数和值是多少。
NSDateComponents的实例不负责回答关于一个日期以外的信息,它是需要先初始化的。例如,如果你初始化一个对象为2004年5月6日,其星期几NSUndefinedDateComponent,不是星期四。要得到正确的星期几,你必须创建一个NSCalendar日历实例,创建一个NSDate对象并使用dateFromComponents:方法,然后使用components:fromDate:检索平周几
 

NSCalendar类:(日历)
 
用于处理时间相关问题。比如比较时间前后、计算日期所的周别等。
 
//在当前日期上加上设定的值得到的日期
NSDate *newdate = [calendar dateByAddingComponents:comps toDate:currentDate  options:0];
 
参考:
 

NSDateFormatter类:  设定时间的格式
 
用于格式化NSDate对象,支持本地化的信息。
setDateStyle和setTimeStyle可同时设置,但不能和setDateFormat共存,只可选其一
 
//设置为中国格式输出
dateFormater.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
 
 
//设置日期、时间显示格式;
- (void)setDateStyle:(NSDateFormatterStyle)style;
- (void)setTimeStyle:(NSDateFormatterStyle)style;
 
NSDateFormatterStyle系统选项包含的Style:
{
    NSDateFormatterNoStyle,
    NSDateFormatterShortStyle,    // “11/23/37” or “3:30pm”.
    NSDateFormatterMediumStyle,     //“Nov 23, 1937”.or “3:30:32pm”.   
    NSDateFormatterLongStyle,     //“November 23, 1937” or “3:30:32pm”.  GMT+08:00
    NSDateFormatterFullStyle     //“Tuesday, April 12, 1952 AD” or “3:30:42pm PST”.
}
 
 
而经常使用的会是setDateFormat方法,可自定义输出格式
- (void)setDateFormat:(NSString *)string;
 
 
Symbol Meaning Example
G era designator G AD
y year
yy
yyyy or y
96
1996
Y year of "Week of Year" Y 1997
u extended year u 4601
U cyclic year name, as in Chinese lunar calendar U 甲子
Q quarter
Q or QQ
QQQ
QQQQ
02
Q2
2nd quarter
q Stand Alone quarter
q or qq
qqq
qqqq
02
Q2
2nd quarter
M month in year
M or MM
MMM
MMMM
MMMMM
09
Sept
September
S
L Stand Alone month in year
L or LL
LLL
LLLL
LLLLL
09
Sept
September
S
w week of year w or ww 27
W week of month W 2
d day in month
d
dd
2
02
D day of year D 189
F day of week in month   2 (2nd Wed in July)
g modified julian day g 2451334
E day of week
E, EE, or EEE
EEEE
EEEEE
Tues
Tuesday
T
e
local day of week
example: if Monday is 1st day, Tuesday is 2nd )
e or ee
eee
eeee
eeeee
2
Tues
Tuesday
T
c Stand Alone local day of week
e or ee
eee
eeee
eeeee
2
Tues
Tuesday
T
a am/pm marker a pm
h hour in am/pm (1~12)
h
hh
7
07
H hour in day (0~23)
H
HH
0
00
k hour in day (1~24)
k
kk
24
24
K hour in am/pm (0~11)
K
KK
0
00
m minute in hour
m
mm
4
04
s second in minute
s
ss
5
05
S
millisecond (maximum of 3 significant digits);
for S or SS, truncates to the number of letters
for SSSS or longer, fills additional places with 0
S
SS
SSS
SSSS
2
23
235
2350
A milliseconds in day A 61201235
z Time Zone: specific non-location
z, zz, or zzz
zzzz
PDT
Pacific Daylight Time
Z
Time Zone: RFC 822
Time Zone: localized GMT
TIme Zone: ISO8601
Z, ZZ, or ZZZ
ZZZZ
ZZZZZ
-0800
GMT-08:00
-08:00
v Time Zone: generic non-location
v
vvvv
PT
Pacific Time or United States (Los Angeles)
V Time Zone: specific non-location, identical to z V PDT
VVVV Time Zone: generic location VVVV United States (Los Angeles)
W week in month   2
' escape for text ' (nothing)
' ' two single quotes produce one ' '

 

Format Pattern Result
yyyy.MM.dd G 'at' HH:mm:ss zzz
1996.07.10 AD at 15:08:56 PDT
EEE, MMM d, ''yy
Wed, July 10, '96
h:mm a
12:08 PM
hh 'o''clock' a, zzzz
12 o'clock PM, Pacific Daylight Time
K:mm a, z
0:00 PM, PST
yyyyy.MMMM.dd GGG hh:mm aaa
01996.July.10 AD 12:08 PM
 
 
 
NSDateFormatter的格式串详解:
a: AM/PM (上午/下午)
A:0~86399999(一天的第A微秒)
c/cc:1~7(一周的第一天,周天为1)
ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)
cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)
d:1~31(月份的第几天,带0)
D:1~366(年份的第几天,带0)
e:1~7(一周的第几天,带0)
E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)
EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)
F:1~5(每月的第几周,一周的第一天为周一)
g: Julian Day Number (number of days since4713BC January1)未知
G~GGG: BC/AD (Era Designator Abbreviated)未知
GGGG: Before Christ/Anno Domini未知
h:1~12(0padded Hour (12hr))带0的时,12小时制
H:0~23(0padded Hour (24hr)) 带0的时,24小时制
k:1~24(0padded Hour (24hr)带0的时,24小时制
K:0~11(0padded Hour (12hr))带0的时,12小时制
        
L/LL:1~12(0padded Month) 第几月
LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec月份简写
LLLL: January/February/March/April/May/June/July/August/September/October/November/December月份全称
        
m:0~59(0padded Minute)分钟
M/MM:1~12(0padded Month)第几月
MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
MMMM: January/February/March/April/May/June/July/August/September/October/November/December
        
q/qq:1~4(0padded Quarter)第几季度
qqq: Q1/Q2/Q3/Q4季度简写
qqqq:1st quarter/2nd quarter/3rd quarter/4th quarter季度全拼
Q/QQ:1~4(0padded Quarter)同小写
QQQ: Q1/Q2/Q3/Q4同小写
QQQQ:1st quarter/2nd quarter/3rd quarter/4th quarter同小写
s:0~59(0padded Second)秒数
S: (rounded Sub-Second)未知
        
u: (0padded Year)未知
        
v~vvv: (General GMT Timezone Abbreviation)常规GMT时区的编写
vvvv: (General GMT Timezone Name)常规GMT时区的名称
        
w:1~53(0padded Week of Year,1st day of week = Sunday, NB:1st week of year starts from the last Sunday of last year)一年的第几周,一周的开始为周日,第一周从去年的最后一个周日起算
W:1~5(0padded Week of Month,1st day of week = Sunday)一个月的第几周
        
y/yyyy: (Full Year)完整的年份
yy/yyy: (2Digits Year) 2个数字的年份
Y/YYYY: (Full Year, starting from the Sunday of the1st week of year)这个年份未知干嘛用的
YY/YYY: (2Digits Year, starting from the Sunday of the1st week of year)这个年份未知干嘛用的
        
z~zzz: (Specific GMT Timezone Abbreviation)指定GMT时区的编写
zzzz: (Specific GMT Timezone Name) Z: +0000 (RFC 822 Timezone) 指定GMT时区的名称
 
eg.
NSString lastModifiedString = @"Mon, 06 Jun 2011 12:47:05 GMT";
 NSDateFormatter *df = [[NSDateFormatter alloc] init];  
 //df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
 df.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
 df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
 df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];  

NSDate date = [df dateFromString:lastModifiedString];  

  

设置上下午显示格式:

NSDateFormatter* formatter = [[[NSDateFormatteralloc] init] autorelease];
 [formatter setDateFormat:dateFormatterString];
 [formatter setAMSymbol:@"am"];    //
 [formatter setPMSymbol:@"pm"];
return [formatter stringFromDate:self];

 

参考:
NSDateFormatter格式一览表:http://www.th7.cn/Program/IOS/201210/109696.shtml
开源项目库文档:http://userguide.icu-project.org/formatparse/datetime (我是没怎么看懂) 

 


NSTimeZone:时区

    NSDate *date = [NSDate date];
    NSLog(@"date:%@",date);
    //系统时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSData *data = [zone data];
    NSLog(@"data:%@",data);
    //时间缩写
    NSString *abbStr = [zone abbreviation];
    NSLog(@"abbStr:%@",abbStr);
    //当地时区
    NSTimeZone *localTime = [NSTimeZonelocalTimeZone];
    NSLog(@"localTime:%@",localTime);
    //和格林尼治时间差
    NSInteger timeOff = [zone secondsFromGMT];
    //视察转化
    NSDate *timeOffDate = [date dateByAddingTimeInterval:timeOff];
    NSLog(@"timeOffDate:%@",timeOffDate);
    //所有地区名称
    NSArray *zoneArrs = [NSTimeZone knownTimeZoneNames];
    NSLog(@"zoneArrs:%@",zoneArrs);
    //遍历
    for (NSString *names in zoneArrs) {
        //时区
        NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:names];
        //设置格式
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateStyle:kCFDateFormatterFullStyle];
        [dateFormatter setTimeStyle:kCFDateFormatterFullStyle];
        [dateFormatter setTimeZone:timeZone];
        NSString *string = [dateFormatter stringFromDate:date];
        NSLog(@"string:%@,[timeZone name]:%@",string,[timeZone name]);
        [dateFormatter release];
        [timeZone release];
    }

获取中国标准时间(没有看见有北京时区的,选了上海的)

    NSDate*date = [NSDate date];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss EEEE";
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    NSLog(@"时间:%@",[dateFormatter stringFromDate:date]);

 


 



应用实例:

(1)获得某一日期是周几

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:11];
[comps setMonth:12];
[comps setYear:2012];
NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
NSDateComponents *weekdayComponents =
    [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
NSLog(@"%d",weekday);   //周二,值为3

//获得昨天的Date
NSDate*yesterday = [NSDatedateWithTimeIntervalSinceNow: -(24 * 60 * 60)];
NSLog(@"yesterday:%@",yesterday);

(2)获得当前时间并取出年/月/日等值

NSDateFormatter*formatter =[[[NSDateFormatteralloc] init] autorelease];
    NSDate *date = [NSDatedate];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *comps = [[[NSDateComponentsalloc] init] autorelease];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
   
    comps = [calendar components:unitFlags fromDate:date];
    int week = [comps weekday];
    int year=[comps year];
    int month = [comps month];
    int day = [comps day];
    int hour = [comps hour];
    int min = [comps minute];
    int sec = [comps second];
   
    NSLog(@"week%d",week);
    NSLog(@"year%d",year);
    NSLog(@"month%d",month);
    NSLog(@"day%d",day);
    NSLog(@"hour%d",hour);
    NSLog(@"min%d",min);

    NSLog(@"sec%d",sec);

(3)//得到毫秒

//得到毫秒
   NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    //[dateFormatter setDateFormat:@"hh:mm:ss"]
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSLog(@"Date%@", [dateFormatter stringFromDate:[NSDatedate]]);
    [dateFormatter release];

(4)计算和所给时间和当天时间的差距

NSCalendar*calendar = [NSCalendarcurrentCalendar];//日历
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date toDate:[NSDate date] options:0];
int year = [components year];
int month = [components month];
int day = [components day];
//三天以内更改显示格式
if (year == 0 && month == 0 && day < 3) {
    if (day == 0) {
        title = NSLocalizedString(@"今天",nil);
    } elseif (day == 1) {
        title = NSLocalizedString(@"昨天",nil);
    } elseif (day == 2) {
        title = NSLocalizedString(@"前天",nil);
    }
}

 

 
posted @ 2013-04-21 18:06  小、  阅读(9904)  评论(0编辑  收藏  举报