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 (我是沒怎么看懂) 
NSDateFormatter的格式串詳解: http://linuxp.blog.163.com/blog/static/17096277201221313933377/  

 


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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM