NSDate存储的是世界标准时(UTC),输出时需要根据时区转换为本地时间
Dates
- NSDate
*now = [[NSDate alloc] init];
- NSTimeInterval
secondsPerDay = 24 * 60 * 60; -
- NSDate
*tomorrow = [[NSDate alloc] initWithTimeIntervalSinc eNow:secondsPerDay]; -
- NSDate
*yesterday = [[NSDate alloc] initWithTimeIntervalSinc eNow:-secondsPerDay]; -
- [tomorrow
release]; - [yesterday
release];
- NSTimeInterval
secondsPerDay = 24 * 60 * 60; -
- NSDate
*today = [[NSDate alloc] init]; - NSDate
*tomorrow, *yesterday; -
- tomorrow
= [today dateByAddingTimeInterval : secondsPerDay]; - yesterday
= [today dateByAddingTimeInterval : -secondsPerDay]; -
- [today
release];
- if
(fabs([date2 timeIntervalSinceDate:date1]) < 60) ...
NSCalendar & NSDateComponents
- NSCalendar
*currentCalendar = [NSCalendar currentCalendar]; - NSCalendar
*japaneseCalendar = [[NSCalendar alloc] initWithCalendarIdentifi er:NSJapaneseCalendar]; - NSCalendar
*usersCalendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];
- NSDateComponents
*components = [[NSDateComponents alloc] init]; -
- [components
setDay:6]; - [components
setMonth:5]; - [components
setYear:2004]; -
- NSInteger
weekday = [components weekday]; // Undefined (== NSUndefinedDateComponent )
- NSDate
*today = [NSDate date]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSDateComponents
*weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; -
- NSInteger
day = [weekdayComponents day]; - NSInteger
weekday = [weekdayComponents weekday];
同样你也可以从NSDateComponents对象来创建NSDate对象:
- NSDateComponents
*components = [[NSDateComponents alloc] init]; -
- [components
setWeekday:2]; // Monday - [components
setWeekdayOrdinal:1]; // The first Monday in the month - [components
setMonth:5]; // May - [components
setYear:2008]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSDate
*date = [gregorian dateFromComponents:components];
- NSDateComponents
*components = [[NSDateComponents alloc] init]; -
- [components
setMonth:11]; - [components
setDay:7]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSDate
*birthday = [gregorian dateFromComponents:components];
下面的示例显示了如何从一个日历置换到另一个日历:
- NSDateComponents
*comps = [[NSDateComponents alloc] init]; -
- [comps
setDay:6]; - [comps
setMonth:5]; - [comps
setYear:2004]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSDate
*date = [gregorian dateFromComponents:comps]; -
- [comps
release]; - [gregorian
release]; -
- NSCalendar
*hebrew = [[NSCalendar alloc] initWithCalendarIdentifi er:NSHebrewCalendar]; -
- NSUInteger
unitFlags = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit; -
- NSDateComponents
*components = [hebrew components:unitFlags fromDate:date]; -
- NSInteger
day = [components day]; // 15 - NSInteger
month = [components month]; // 9 - NSInteger
year = [components year]; // 5764
历法计算
- NSDate
*today = [[NSDate alloc] init]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSDateComponents
*offsetComponents = [[NSDateComponents alloc] init]; -
- [offsetComponents
setHour:1]; - [offsetComponents
setMinute:30]; -
- //
Calculate when, according to Tom Lehrer, World War III will end - NSDate
*endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
- NSDate
*today = [[NSDate alloc] init]; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- //
Get the weekday component of the current date - NSDateComponents
*weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today]; -
-
-
- NSDateComponents
*componentsToSubtract = [[NSDateComponents alloc] init]; -
- [componentsToSubtract
setDay: 0 - ([weekdayComponents weekday] - 1)]; -
- NSDate
*beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0]; -
-
-
- NSDateComponents
*components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: beginningOfWeek]; -
- beginningOfWeek
= [gregorian dateFromComponents:components];
- NSDate
*today = [[NSDate alloc] init]; -
- NSDate
*beginningOfWeek = nil; -
- BOOL
ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];
- NSDate
*startDate = ...; - NSDate
*endDate = ...; -
- NSCalendar
*gregorian = [[NSCalendar alloc] initWithCalendarIdentifi er:NSGregorianCalendar]; -
- NSUInteger
unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; -
- NSDateComponents
*components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; -
- NSInteger
months = [components month]; - NSInteger
days = [components day];
- @implementation
NSCalendar (MySpecialCalculations) -
- -(NSInteger)daysWithinEraFromDate:(NSDate
*) startDate toDate:(NSDate *) endDate { -
NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:startDate]; -
-
NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:endDate]; -
-
return endDay-startDay; - }
-
- @end
- @implementation
NSCalendar (MyOtherMethod) -
- -(NSInteger)
daysFromDate:(NSDate *) startDate toDate:(NSDate *) endDate { -
-
NSCalendarUnit units=NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; -
-
NSDateComponents *comp1=[self components:units fromDate:startDate]; -
NSDateComponents *comp2=[self components:units fromDate endDate]; -
-
[comp1 setHour:12]; -
[comp2 setHour:12]; -
-
NSDate *date1=[self dateFromComponents: comp1]; -
NSDate *date2=[self dateFromComponents: comp2]; -
-
return [[self components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0] day]; - }
-
- @end
- -(BOOL)isDateThisWeek:(NSDate
*)date { -
-
NSDate *start; -
NSTimeInterval extends; -
-
NSCalendar *cal=[NSCalendar autoupdatingCurrentCalen dar]; -
NSDate *today=[NSDate date]; -
-
BOOL success= [cal rangeOfUnit:NSWeekCalendarUnit startDate:&start interval: &extends forDate:today]; -
-
if(!success) -
return NO; -
-
NSTimeInterval dateInSecs = [date timeIntervalSinceReferen ceDate]; -
NSTimeInterval dayStartInSecs= [start timeIntervalSinceReferen ceDate]; -
-
if(dateInSecs > dayStartInSecs && dateInSecs < (dayStartInSecs+extends)){ -
return YES; -
} -
else { -
return NO; -
} - }
来源:http://blog.csdn.net/lingedeng/article/details/6996599
1、获取当前时间
- NSDateFormatter*formatter
= [[NSDateFormatteralloc] init]; - [formatter
setDateFormat:@"yyyy-MM-dd hh:mm:ss" ]; - NSString
*locationString=[formatter stringFromDate: [NSDate date]];
另外的方法:
- -(NSString
*)getDate - {
- NSDateFormatter*formatter
= [[NSDateFormatteralloc] init]; - [formatter
setDateFormat:@"yyyy-MM-dd EEEE ];HH:mm:ss a" - NSString
*locationString=[formatter stringFromDate: [NSDate date]]; - [formatter
release]; - return
locationString; - }
//大写的H日期格式将默认为24小时制,小写的h日期格式将默认为12小时
//不需要特别设置,只需要在dataFormat里设置类似"yyyy-MMM-dd"这样的格式就可以了
日期格式如下:
y
M
w
W
D
d
F
E
a
H
k
K
h
m
s
S
z
Z
2、NSTimer定时器的基本操作方式
NSTimer是Cocoa中比较常用的定时器类,基本操作如下:
handleTimer方法可以自行定义。在需要的地方创建timer即可,handleTimer就可以每0.5秒执行一次。
-
- (void) handleTimer: (NSTimer *) timer - {
-
//在这里进行处理 - }
- NSTimer
*timer; - timer
= [NSTimer scheduledTimerWithTimeIn terval: 0.5 target: self selector: @selector(handleTimer:)userInfo: nil repeats: YES];
3、定时器
设置定时器下面显示的定时器将在一秒钟后触发,并一直重复直到定时器被禁用。定时器每次激活时,就会调用发送选择器消息的目标来进行初始化。回调方法带有一个参数,就是定时器本身.要禁用一个定时器,给它发送invalidate消息,这将释放定时器对象并把它从当前运行循环中删除。
- NSTime
*timer ; - timer
= [NSTimer scheduledTimerWithTimeIn terval:1.0target:self selector:@selector(handlTimer:) userInfo:nilrepeats:YES]; -
- -
(void)handleTimer:(NSTimer *)timer{ - printf("timer
count: ,%d" count++); - if(count
> 3) - {
- [timer
invalidate]; - }
来源:
1. 使用 NSTimeZone 取得世界各地时间的方法
- //取得目前已知的所有地里名称
- NSArray
*timeZoneNames = [NSTimeZone knownTimeZoneNames]; -
- //取得本地目前时间
- NSDate
*date = [NSDate date]; -
- for(NSString
*name in timeZoneNames) { - NSTimeZone
*timezone = [[NSTimeZone alloc] initWithName:name]; - NSDateFormatter
*formatter = [[NSDateFormatter alloc] init]; -
- //设定时间格式
- [formatter
setDateFormat:@"YYYY-MM-d HH:mm:ss" ]; -
- //设定时区
- [formatter
setTimeZone:timezone]; -
- //时间格式正规化并做时区校正
- NSString
*correctDate = [formatter stringFromDate:date]; -
- NSLog(@"地点:%@
当地时间:%@" ,[timezonename], correctDate); -
- [formatter
release]; - [timezone
release]; - }
来源:
2. 取得 iOS 系统日期与星期的方法
- NSDateFormatter
*formatter = [[NSDateFormatter alloc] init]; - NSDate
*date = [NSDate date]; -
- //正规化的格式设定
- [formatter
setDateFormat:@"YYYY-MM-dd' 'EEEE" ]; -
- //正规化取得的系统时间并显示
- dateLabel.text
= [formatter stringFromDate:date];
当然 NSFormatter 能正规化的格式不只这些,想知道其他的参数可以参考关于 NSDateFormatter 的二三事一文。
3. 取得 iOS 系统时间的方法
- NSDateFormatter
*formatter = [[NSDateFormatter alloc] init]; - NSDate
*date = [NSDate date]; -
- //正规化的格式设定
- [formatter
setTimeStyle:NSDateFormatterFullStyle ]; -
- //正规化取得的系统时间并显示
- timeLabel.text
= [formatter stringFromDate:date]; -
- [formatter
release];
- [formatter
setTimeStyle:NSDateFormatterFullStyle ]; - [formatter
setTimeStyle:NSDateFormatterLongStyle ]; - [formatter
setTimeStyle:NSDateFormatterMediumSty le]; - [formatter
setTimeStyle:NSDateFormatterShortStyl e];
最后,如果要让时间与现实时间同步可以考虑实做计时器 Timer 来解决此问题,详细的设定方式可参阅 Timer / 计时器的基本使用方法。
来源:http://furnacedigital.blogspot.com/2011/01/blog-post.html#more
4. Timer / 计时器的基本使用方法
- //自行定义的函式,用来设定使用Timer/计时器的相关参数
- -(void)initializeTimer
{ -
- //设定Timer触发的频率,每秒30次
- float
theInterval = 1.0/30.0; - fpsLabel.text
= [NSString stringWithFormat:@"%0.3f", theInterval]; -
- //正式启用Timer,selector是设定Timer触发时所要呼叫的函式
- [NSTimer
scheduledTimerWithTimeIn terval:theInterval - target:self
- selector:@selector(countTotalFrames:)
- userInfo:nil
- repeats:YES];
- }
- -(void)countTotalFrames:(NSTimer
*)theTimer { - frameCount
++; - framesLabel.text
= [NSString stringWithFormat:@"%d", frameCount]; - }
来源:http://furnacedigital.blogspot.com/2010/11/timer.html