当我们开发中经常遇到时间戳转换成时间,我们遇到的时间戳分两种类型.
1.2233445673
2.3456677890498
这两种其实没什么区别,13为的后三位是精度值
我们计算的时候可以去掉
1,计算当前的时间
NSDate *nowDate = [NSDate date];
获取到当前时间:
nowDate=====2015-07-18 03:16:50 +0000
2,把当前时间转成"yyyy-MM-dd"
NSDateFormatter *etimeFormate = [[NSDateFormatter alloc]init];
[etimeFormate setDateFormat:@"yyyy-MM-dd"];
NSString *etimeStr = [etimeFormate stringFromDate:[NSDate date]];
3.时间戳转换成日期
stime = @"1234567890123" ;
NSTimeInterval time = ([strTime doubleValue]/1000);
NSDate *date= [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *CurrDate = [formatter stringFromDate:date];
把同一时间戳转换成时间
NSDateFormatter *twoFormat = [[NSDateFormatter alloc]init];
[twoFormat setDateFormat:@"HH:mm:ss"];
NSString *timeDate = [twoFormat stringFromDate:date];
4.计算几天前的日期
//更改当前时间格式
NSInteger dis = 30;//多少天前
NSTimeInterval oneDay = 24*60*60*1;//一天的时间
NSDate *nowDate = [NSDate date];
NSDate *stimeDate = [nowDate initWithTimeIntervalSinceNow:-oneDay * dis];//用当前时间转换
NSDateFormatter *stimeFormatter = [[NSDateFormatter alloc]init];//转换
[stimeFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *stimeStr = [stimeFormatter stringFromDate:stimeDate]
总结:
我们经常用到的就是NSDateFormatter stringFromDate
NSDate有几种方法
- (instancetype)initWithTimeIntervalSinceNow:(NSTimeInterval)secs;//从现在算
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)secs;//1970年开始
- (instancetype)initWithTimeInterval:(NSTimeInterval)secsToBeAdded sinceDate:(NSDate *)date;
星期的转换方式和天的转换
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
now=[NSDate date];
comps = [calendar components:unitFlags fromDate:now];
NSInteger week = [comps weekday];//特殊说明:week = 1 周日 =2 周一 =3周二 ... 7周六
//下面的大家打印一下就能看明白,程序员要动手,不能光看
NSInteger month = [comps month];
NSInteger day = [comps day];
NSInteger hour = [comps hour];
NSInteger min = [comps minute];
NSInteger sec = [comps second];