[转]Objective-c NSDate 取时间,日期,星期,毫秒等

NSDate


//得到当前的日期
 NSDate *date = [NSDate date];
 NSLog(@"date:%@",date);
 
 //得到(24 * 60 * 60)即24小时之前的日期,dateWithTimeIntervalSinceNow:
 NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(24 * 60 * 60)];
 NSLog(@"yesterday:%@",yesterday);


NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
 NSDate *date = [NSDate date];
 [formatter setTimeStyle:NSDateFormatterMediumStyle];
 NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
 NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
 NSInteger unitFlags = NSYearCalendarUnit | 
                       NSMonthCalendarUnit |
                       NSDayCalendarUnit | 
                       NSWeekdayCalendarUnit | 
                       NSHourCalendarUnit |
                       NSMinuteCalendarUnit |
                       NSSecondCalendarUnit;
 //int week=0;
 comps = [calendar components:unitFlags fromDate:date];
 int week = [comps weekday]; 
 int year=[comps year]; 
 int month = [comps month];
 int day = [comps day];
 //[formatter setDateStyle:NSDateFormatterMediumStyle];
 //This sets the label with the updated time.
 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);

 

//得到毫秒
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] 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:[NSDate date]]);
 [dateFormatter release];

 

 

 

 

 

 

 

个人会喜欢用的方法

NSDate

  - (NSString *)description;

    YYYY-MM-DD HH:MM:SS ±HHMM的格式表示时间。

    其中 "±HHMM" 表示与GMT的存在多少小时多少分钟的时区差异。比如,若时区设置在北京,则 "±HHMM" 显示为 "+0800"

 

将结果 进行 subString操作取得想要的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值