iOS:日期 时间类操作 NSDate、calendar、formatter、components、locale、timeZone - houseq 的专栏 - 博客频道 - CSDN.NET

来源:互联网 发布:淘宝直播刷人气 编辑:程序博客网 时间:2024/05/17 20:22

iOS:日期 时间类操作 NSDate、calendar、formatter、components、locale、timeZone

.
分类: iOS iOS.sdk.Data Management 2014-05-06 15:21756人阅读评论(0)收藏举报
nsdateios日历components

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html

==============================

============NSDate============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html + http://jiapumin.iteye.com/blog/1988031

--简介:代表着一个单独的时间点;

--常用方法:

------------Creating and Initializing Date Objects(创建)------------

--类方法:

+ (id)date;返回当前时间
+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs; 返回以当前时间为基准,然后过了secs秒的时间
+ (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs;返回以2001/01/01 GMT为基准,然后过了secs秒的时间
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)secs;返回以1970/01/01 GMT为基准,然后过了secs秒的时间
--实例方法:各方法效果都类似相关类方法

------------Getting Temporal Boundaries------------

+ (id)distantFuture;返回很多年以后的未来的某一天。
比如你需要一个比现在(Now)晚(大)很长时间的时间值,则可以调用该方法。测试返回了4000/12/31 16:00:00
+ (id)distantPast;返回很多年以前的某一天。
比如你需要一个比现在(Now)早(小)大很长时间的时间值,则可以调用该方法。测试返回了公元前0001/12/31 17:00:00

------------Comparing Dates(比较)------------

- (BOOL)isEqualToDate:(NSDate *)otherDate;

- (NSDate *)earlierDate:(NSDate *)anotherDate;与anotherDate比较,返回较早的那个日期
- (NSDate *)laterDate:(NSDate *)anotherDate;与anotherDate比较,返回较晚的那个日期
- (NSComparisonResult)compare:(NSDate *)other;
该方法用于排序时调用:
a.当实例保存的日期值与anotherDate相同时返回NSOrderedSame
b.当实例保存的日期值晚于anotherDate时返回NSOrderedDescending
c.当实例保存的日期值早于anotherDate时返回NSOrderedAscending

------------Getting Time Intervals(时间戳)------------

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;以refDate为基准时间,返回实例保存的时间与refDate的时间间隔
- (NSTimeInterval)timeIntervalSinceNow;以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔
- (NSTimeInterval)timeIntervalSince1970;以1970/01/01 GMT为基准时间,返回实例保存的时间与1970/01/01 GMT的时间间隔
- (NSTimeInterval)timeIntervalSinceReferenceDate;以2001/01/01 GMT为基准时间,返回实例保存的时间与2001/01/01 GMT的时间间隔
+ (NSTimeInterval)timeIntervalSinceReferenceDate;以2001/01/01 GMT为基准时间,返回当前时间(Now)与2001/01/01 GMT的时间间隔

备注:

------------时间戳:直接显示、NSDateFormatter显示------------

时间戳定义:从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数;

[objc] view plaincopy在CODE上查看代码片
  1. NSDate *date = [NSDate dateWithTimeIntervalSince1970:0.0];      
  2. NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];  
  3. [outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  
  4. NSString *timestamp_str = [outputFormatter stringFromDate:date];  
  5. NSLog(@"%@",date);  
  6. NSLog(@"%@",timestamp_str);  
  7. NSLog(@"%@,%@",[outputFormatter.locale localeIdentifier],[outputFormatter.timeZone name]);  
  8. //输出:1970-01-01 00:00:00 +0000  
  9. //输出:1970-01-01 08:30:00  
  10. //en_US,Asia/Harbin  
1.输出1显示了时间戳实质,格林威治区的时间,输出2显示了时间戳对应的当地时间

2.将上例中的date换为 = [NSDate date];则输出1格式显示的的时间跟当地时间可能不对应,它的值是根据定义(格林威治时区)来的;输出2格式显示的是当地时间,跟1时间差为当地所在的时区值。

[objc] view plaincopy在CODE上查看代码片
  1. //现在的时间 例:2014-05-19 16:38:12  
  2. double date = [[NSDate date] timeIntervalSince1970];      
  3. NSCalendar *calendar = [NSCalendar currentCalendar];  
  4. NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate dateWithTimeIntervalSince1970:date]];  
  5. //当天零点 例:2014-05-19 00:00:00  
  6. double date1 = [[calendar dateFromComponents:components] timeIntervalSince1970];  
  7. //取当前时间的 时分秒  
  8. double interval = date - date1;  
  9. NSLog(@"%@",[NSDate dateWithTimeIntervalSince1970:interval]);  
  10. //输出:1970-01-01 16:38:12 +0000  
  11. NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];  
  12. [outputFormatter setDateFormat:@"HH:mm:ss"];  
  13. NSString *timestamp_str = [outputFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:interval]];  
  14. NSLog(@"%@",timestamp_str);  
  15. //输出:01:08:12  

1.注意上例中的data1,如果用NSLog直接输出,它的值不是2014-05-19 00:00:00 +0000,而是2014-05-18 16:00:00 +0000。calendar和components处理对象都是相对当地时间而言。注意区别。

2.跟时间相关使用的时候,注意区分当前时间戳是表示一个绝对时间,还是一段时间间距(输出2),

----总结:

a.时间戳/date的值(程序存储的值)总是标准时间(格林威治区的时间),它跟当地时间存在一个对应关系。

b.当时间戳/date输出的时候,区别它显示的是当地的时间还是标准时间,不能仅仅看它是否跟当地时间相等而去判断一个时间戳的值对错;

c.注意NSDateFormatter、NSCalendar、NSDateComponents这些类有时区的属性,默认的是当地时区,所以它处理的结果都是对应着当地的时间情况,但存储的时间不一定符合当地时间;

------------Adding a Time Interval------------

- (id)dateByAddingTimeInterval:(NSTimeInterval)ti;返回实例保存ti秒之后的时间

------------Representing Dates as Strings------------

– description;以YYYY-MM-DD HH:MM:SS ±HHMM的格式表示时间(2014-05-06 02:11:47 +0000)。其中 "±HHMM" 表示与GMT的存在多少小时多少分钟的时区差异。比如,若时区设置在北京,则 "±HHMM" 显示为 "+0800"。

- (NSString *)descriptionWithLocale:(id)locale;

==================================

============NSCalendar============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html + http://blog.csdn.net/nslog/article/details/11612877

--简介:Calendars encapsulate information about systems of reckoning time in which the beginning, length, and divisions of a year are defined。

--常用方法:

------------Initializing------------

+ (id)currentCalendar;取得当前用户的逻辑日历(logical calendar)

+ (id)autoupdatingCurrentCalendar;取得当前用户的逻辑日历(logical calendar)

- (id)initWithCalendarIdentifier:(NSString *)identifier;

identifier的范围可以是:NSGregorianCalendar 阳历、NSBuddhistCalendar 佛历、NSChineseCalendar 中国日历、NSHebrewCalendar 希伯来日历、NSIslamicCalendar 伊斯兰日历、NSIslamicCivilCalendar 伊斯兰民事日历、NSJapaneseCalendar 日本日历

- (void)setLocale:(NSLocale *)locale;设置区域
- (void)setTimeZone:(NSTimeZone *)tz;设置时区
- (void)setFirstWeekday:(NSUInteger)value;设定每周的第一天从星期几开始,比如:. 如需设定从星期日开始,则value传入1;. 如需设定从星期一开始,则value传入2;
- (void)setMinimumDaysInFirstWeek:(NSUInteger)value;设定作为(每年及每月)第一周必须包含的最少天数,比如: 如需设定第一周最少包括7天,则value传入7;
------------Getting Information About a Calendar------------

- (NSString *)calendarIdentifier返回日历标示符(identifier)。
- (NSLocale *)locale;返回日历指定的地区信息。
- (NSTimeZone *)timeZone;返回日历指定的时区信息。
- (NSUInteger)firstWeekday;

- (NSRange)maximumRangeOfUnit:(NSCalendarUnit)unit;返回单元的最大范围。

就Gregorian来说有:

NSEraCalendarUnit => 0 - 2;

NSYearCalendarUnit => 1 - 10000;

NSMonthCalendarUnit = 1 - 12;

NSDayCalendarUnit = 1 - 31;

NSHourCalendarUnit = 0 - 24;

NSMinuteCalendarUnit = 0 - 60;

NSSecondCalendarUnit = 0 - 60;

NSWeekCalendarUnit = 1 - 53;

NSWeekdayCalendarUnit = 1 - 7

- (NSRange)minimumRangeOfUnit:(NSCalendarUnit)unit;返回单元的最小范围。

- (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date
返回某个特定时间(date)其对应的小的时间单元(smaller)在大的时间单元(larger)中的顺序,比如:

要取得2008/11/12在当月的第几周则可以这样调用该方法:[calendar ordinalityOfUnit:NSWeekOrdinalCalendarUnit inUnit: NSWeekCalendarUnit forDate: someDate]; 注: someDate存放了2008/11/12

- (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date

返回某个特定时间(date)其对应的小的时间单元(smaller)在大的时间单元(larger)中的范围,比如:
. 要取得2008/11/12在所在月份的日期范围则可以这样调用该方法:[calendar ordinalityOfUnit:NSDayCalendarUnit inUnit: NSMonthCalendarUnit forDate:fDate]; 则返回1-31。注: fDate存放了2008/11/12
- (BOOL)rangeOfUnit:(NSCalendarUnit)unit startDate:(NSDate **)sDate interval:(NSTimeInterval *)unitSecs forDate:(NSDate *)date;
用于返回日期date(参数)所在的那个日历单元unit(参数)的开始时间(sDate)。其中参数unit指定了日历单元,参数sDate用于返回日历单元的第一天,参数unitSecs用于返回日历单元的长度(以秒为单位),参数date指定了一个特定的日期。如果startDate和interval均为可计算的,那么函数返回YES否则返回NO.注意statDate参数类型

------------Calendrical Calculations------------

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date;calendar根据unit格式将date分解成指定components

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts;calendar根据unit格式,返回俩个日期相差的components(这里components代表着a duration of time)

- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts;返回一个时间,calendar在date基础上增加了components(这里components也代表着a duration of time)后;
- (NSDate *)dateFromComponents:(NSDateComponents *)comps;calendar用components计算出来的date;

========================================

============NSDateComponents============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html

--简介:NSDateComponents encapsulates the components of a date in an extendable, object-oriented manner;( It is used to specify a date by providing the temporal components that make up a date and time: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. An NSDateComponents object is not required to define all the component fields. When a new instance of NSDateComponents is created the date components are set to NSUndefinedDateComponent).

--常用方法:-set/get era/ year/ month/ date/ day/ hour/ minute/ second/ week/ weekday/ weekdayOrdinal/ quarter/ calendar/ timeZone/ weekOfMonth/ weekOfYear...

备注:An NSDateComponents object is meaningless in itself; you need to know what calendar it is interpreted against, and you need to know whether the values are absolute values of the units, or quantities of the units.

======================================

============NSDateFormatter============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

--简介:用于在nsdate和字符串显示之间转换;

--基本用法:Converting Objects + Managing Attributes  +Managing  Styles;

[objc] view plaincopy在CODE上查看代码片
  1. NSDate* aDate = ...;  
  2. NSDateFormatter* fmt = [[NSDateFormatter alloc] init];  
  3. fmt.dateStyle = kCFDateFormatterShortStyle;  
  4. fmt.timeStyle = kCFDateFormatterShortStyle;  
  5. fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];  
  6. NSString* dateString = [fmt stringFromDate:aDate];  
其中NSDateFormatterStyle样式为(dateStyle和timeStyle的值):默认的locale
[objc] view plaincopy在CODE上查看代码片
  1. typedef CF_ENUM(CFIndex, CFDateFormatterStyle) {    // date and time format styles  
  2.     kCFDateFormatterNoStyle = 0,       // 无输出  
  3.     kCFDateFormatterShortStyle = 1,    // 10/29/12, 2:27 PM  
  4.     kCFDateFormatterMediumStyle = 2,   // Oct 29, 2012, 2:36:59 PM  
  5.     kCFDateFormatterLongStyle = 3,     // October 29, 2012, 2:38:46 PM GMT+08:00  
  6.     kCFDateFormatterFullStyle = 4      // Monday, October 29, 2012, 2:39:56 PM China Standard Time  
  7. };  
--Managing Formats(自定义日期时间格式):fmt.dateFormat = @"yyyy-MM-dd  HH:mm:ss";

G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如 2

e: 1~7 (一周的第几天, 带0)

EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
K:时,12小时制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒

Q/QQ: 1~4 (0 padded Quarter) 第几季度

QQQ: Q1/Q2/Q3/Q4 季度简写
QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter 季度全拼

--Managing (AM/PM、Weekday、Month...) Symbols

================================

============NSLocale============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/Reference/Reference.html + http://my.oschina.net/hmj/blog/126355

--简介:NSLocale封装了关于语言,文化以及技术约定和规范的信息。用它可以获取用户的本地化信息设置,例如货币类型,国家,语言,数字,日期格式的格式化,提供正确的地理位置显示等等。

================================

============NSTimeZone============

--参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/Reference/Reference.html + http://my.oschina.net/yongbin45/blog/151376

--方法备注:

[objc] view plaincopy在CODE上查看代码片
  1. - (NSInteger)secondsFromGMTForDate:(NSDate *)aDate; //得到该时区与日期的偏移量秒数  
  2. - (NSInteger)secondsFromGMT;//得到该时区与标准时区偏移量秒数  
 利用方法的返回值,可以在不同时区对应相应时间戳,进行相关操作、判断。
----说明:

1."GMT+0800"这种格式指:偏移量。

2.想要获取NSTimeZone 格林威治所在的时区对象,可以通过:

--A.由时区名字创建,方法+ (id)timeZoneWithName:(NSString *)tzName; 时区名字可以通过NSTimeZone 的+ (NSArray *)knownTimeZoneNames方法查看;

--B.由时区名称缩写创建,方法+ (id)timeZoneWithAbbreviation:(NSString *)abbreviation; 时区名称缩写 俩中形式:一种为“GMT”这种;一种为"GMT+0800"。前者可以通过NSTimeZone 的+ (NSDictionary *)abbreviationDictionary;方法查看。

3.GMT:格林尼治时间或世界标准时间(零度经线时区时间)/零时区所在时区缩写。



.
  • 上一篇iOS:Xcode Build Settings && info.plist
  • 下一篇iOS:属性、修饰词(内存管理) 及其对应成员变量 、ARC
  • .
0 0
原创粉丝点击