创建当前时间
[cpp] view
plaincopyprint?
- NSDate *date = [NSDate date];
从现在开始的24小时
NSTimeInterval a_day = 24*60*60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:a_day];
根据已有日期创建日期
[cpp] view
plaincopyprint?
- NSTimeInterval a_day = 24*60*60;
- NSDate *date = [NSDate date];
- NSDate *tomorrow = [date addTimeInterval: date];
日期比较
[cpp] view
plaincopyprint?
- BOOL isEqual = [date isEqualToDate:tomorrow];
- f(isEqual){
- NSLog(@"equal");
//获取较早的日期
[cpp] view
plaincopyprint?
- NSDate *earlier_date = [tomorrow earlierDate:date];
- NSLog(@"earlierDate = %@",earlierDate);
//较晚的日期
[cpp] view
plaincopyprint?
- NSDate *laterDate = [tomorrow laterDate:date];
- NSLog(@"laterDate = %@",laterDate);
//两个日期之间相隔多少秒
[cpp] view
plaincopyprint?
- NSTimeInterval secondsInterval= [date timeIntervalSinceDate:tomorrow];
- NSLog(@"secondsInterval= %lf",secondsInterval);
//通过NSCalendar类来创建日期
[cpp] view
plaincopyprint?
- NSDateComponents *comps = [[NSDateComponentsalloc]init];
- [comps setMonth:01];
- [comps setDay:31];
- [comps setYear:2013];
- NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDate *date = [calendar dateFromComponents:comps];
//从已有日期获取日期
[cpp] view
plaincopyprint?
- unsigned units = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
- NSDateComponents *_comps = [calendar components:units fromDate:date];
- NSInteger month = [_comps month];
- NSInteger year = [_comps year];
- NSInteger day = [_comps day];
- //NSDateFormatter实现日期的输出
- NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
- [formatter setDateStyle:NSDateFormatterFullStyle];//直接输出的话是机器码
- //或者是手动设置样式[formatter setDateFormat:@"yyyy-mm-dd"];
- NSString *dateString = [formatter stringFromDate:date];
- NSLog(@"dateString = %@",dateString);
- NSLog(@"formater = %@",formatter);
//获取日期格式对象
[cpp] view
plaincopyprint?
- - (NSDateFormatter *)getDateFormatter {
- if (dateFormatter == nil) {
- dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
- [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
- }
- return dateFormatter;
- }
时间: 2024-11-05 14:30:55