iOS 时间与时间戳相互转化以及基本应用

一、时间戳与标准时间之间的相互转化
1.获取标准时间

//获取系统时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//获取系统时区 **此时不设置时区是默认为系统时区
formatter.timeZone = [NSTimeZone systemTimeZone];
//指定时间显示样式: HH表示24小时制 hh表示12小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//只显示时间
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
//只显示日期
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *date = [formatter stringFromDate:[NSDate date]];
NSLog(@"nowTime:%@",date);

2.获取时间戳

NSDate *second = [NSDate date];
long secondTimeZone = [second timeIntervalSince1970];

3.标准时间转化时间戳

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//指定时间显示样式: HH表示24小时制 hh表示12小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *lastTime = @"2017-01-23 17:22:00";
NSDate *lastDate = [formatter dateFromString:lastTime];
//以 1970/01/01 GMT为基准,得到lastDate的时间戳
long firstStamp = [lastDate timeIntervalSince1970];
NSLog(@"firstStamp:%ld",firstStamp);
扩展
//以 lastTime GMT为基准,得到的时间戳
long secondStamp = [[NSDate date] timeIntervalSinceDate:lastDate];
//以 此时 GMT为基准,得到lastDate的时间戳
long thirdStamp = [lastDate timeIntervalSinceNow];
//以 2001/01/01 GMT为基准,得到的时间戳
long fourthStamp = [[NSDate date] timeIntervalSinceReferenceDate];

4.时间戳转化成标准时间

//时间戳转化成时间
NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
[stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//以 1970/01/01 GMT为基准,然后过了secs秒的时间
NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:1485159493];
NSLog(@"时间戳转化时间 >>> %@",[stampFormatter stringFromDate:stampDate]);
扩展
//以 2001/01/01 GMT为基准,然后过了secs秒的时间
NSDate *stampDate = [NSDate dateWithTimeIntervalSinceReferenceDate:506852179];
//以 现在的时间 GMT为基准,然后过了secs秒的时间
NSDate *stampDate3 = [NSDate dateWithTimeIntervalSinceNow:7*24*3600];
NSLog(@"时间戳转化时间2 >>> %@",[stampFormatter stringFromDate:stampDate2]);
NSLog(@"时间戳转化时间3 >>> %@",[stampFormatter stringFromDate:stampDate3]);

二、分别根据时间戳与标准时间计算: 几分钟之前,几小时之前...

调用该方法,传入后台返回的时间戳
- (NSString *)timeBeforeInfoWithString:(NSTimeInterval)timeIntrval{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//获取此时时间戳长度
NSTimeInterval nowTimeinterval = [[NSDate date] timeIntervalSince1970];
int timeInt = nowTimeinterval - timeIntrval; //时间差
int year = timeInt / (3600 * 24 * 30 *12);
int month = timeInt / (3600 * 24 * 30);
int day = timeInt / (3600 * 24);
int hour = timeInt / 3600;
int minute = timeInt / 60;
int second = timeInt;
if (year > 0) {
return [NSString stringWithFormat:@"%d年以前",year];
}else if(month > 0){
return [NSString stringWithFormat:@"%d个月以前",month];
}else if(day > 0){
return [NSString stringWithFormat:@"%d天以前",day];
}else if(hour > 0){
return [NSString stringWithFormat:@"%d小时以前",hour];
}else if(minute > 0){
return [NSString stringWithFormat:@"%d分钟以前",minute];
}else{
return [NSString stringWithFormat:@"刚刚"];
}
}

三、有效期

例:有效期为7天
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//获取七日后的时间戳
NSDate *stampTimeZone = [NSDate dateWithTimeIntervalSinceNow:7*24*3600];
NSLog(@"stampTimeZone: %@",[formatter stringFromDate:stampTimeZone]);
例:有效期为本周日
NSDateComponents:可以简单且有效的获取某个时间点对应的“年”,“月”,“日”,“周”,“时”,“分”,“秒”等信息;还可以表示时间段,例如:一周,一个月,10年,5天,10分钟,10秒等等。
- (void)getMondayAndSunday{
NSDate *nowDate = [NSDate date];
//先创建一个 遵循某个历法 日历对象
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierISO8601];
NSDateComponents *compomemts = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay   fromDate:nowDate];
// 获取今天是周几 (iOS规定的)星期天是1 星期一是2
NSInteger weekday = compomemts.weekday;
// 获取今天是几号
NSInteger day = compomemts.day;
NSLog(@"weekday:%ld \t day:%ld",weekday,day);
// 计算当前日期分别于 周一和周天 的相差天数
long mondayValue,sundayValue;
if (weekday == 1) {
mondayValue = -6;
sundayValue = 0;
}else {
mondayValue = [calendar firstWeekday] - weekday + 1;
sundayValue = 8 - weekday;
}
NSLog(@"mondayValue: %ld \t sundayValue: %ld",mondayValue,sundayValue);
// 在当前日期(去掉时分秒)基础上加上差的天数
NSDateComponents *mondayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
[mondayComp setDay:day + mondayValue];
NSDate *mondayOfWeek = [calendar dateFromComponents:mondayComp];
NSDateComponents *sundayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay   fromDate:nowDate];
[sundayComp setDay:day + sundayValue];
NSDate *sundayOfWeek = [calendar dateFromComponents:sundayComp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSString *monday = [formatter stringFromDate:mondayOfWeek];
NSString *sunday = [formatter stringFromDate:sundayOfWeek];
NSLog(@"monday:%@ \t sunday:%@",monday, sunday);
}

四、计算星座
调用此方法,传入参数格式为: YYYY-MM-DD

/**
摩羯座 12月22日------1月19日
水瓶座 1月20日-------2月18日
双鱼座 2月19日-------3月20日
白羊座 3月21日-------4月19日
金牛座 4月20日-------5月20日
双子座 5月21日-------6月21日
巨蟹座 6月22日-------7月22日
狮子座 7月23日-------8月22日
处女座 8月23日-------9月22日
天秤座 9月23日------10月23日
天蝎座 10月24日-----11月21日
射手座 11月22日-----12月21日
*/
-(NSString *) getConstellationInfo:(NSString *)date {
//计算月份
NSString *retStr=@"";
NSString *birthStr = [date substringFromIndex:5];
int month=0;
NSString *theMonth = [birthStr substringToIndex:2];
if([[theMonth substringToIndex:0] isEqualToString:@"0"]){
month = [[theMonth substringFromIndex:1] intValue];
}else{
month = [theMonth intValue];
}
//计算天数
int day=0;
NSString *theDay = [birthStr substringFromIndex:3];
if([[theDay substringToIndex:0] isEqualToString:@"0"]){
day = [[theDay substringFromIndex:1] intValue];
}else {
day = [theDay intValue];
}
if (month<1 || month>12 || day<1 || day>31){
return @"错误日期格式!";
}
if(month==2 && day>29) {
return @"错误日期格式!!";
}else if(month==4 || month==6 || month==9 || month==11) {
if (day>30) {
return @"错误日期格式!!!";
}
}
NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
NSString *astroFormat = @"102123444543";
retStr=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(month*2-(day < [[astroFormat substringWithRange:NSMakeRange((month-1), 1)] intValue] - (-19))*2,2)]];
return [NSString stringWithFormat:@"%@座",retStr];
}

五、根据生日计算年龄

根据出生日期计算年龄会经常用到,我开始想用时间戳的方法来解决,简单快速,但是这样并不正确,因为没有考虑到闰年的情况。所以这样实现是不严谨的。

NSDateFormatter*df = [[NSDateFormatter alloc] init];//格式化
[df setDateFormat:@"yyyy/MM/dd"];
NSDate *date = [df dateFromString:@"2001/01/01"];
NSTimeInterval dateDiff = [date timeIntervalSinceNow];
long age = fabs(dateDiff/(60*60*24))/365;
NSLog(@"年龄是:%ld", age);

下面上正确的代码:

NSDateFormatter*df = [[NSDateFormatter alloc] init];//格式化
[df setDateFormat:@"yyyy/MM/dd"];
NSString *dateStr = @"2001/01/01";
NSTimeInterval dateDiff = [[df dateFromString:dateStr] timeIntervalSinceNow];
long age = fabs(dateDiff/(60*60*24))/365;
NSLog(@"年龄是:%@",[NSString stringWithFormat:@"%ld岁",age]);
NSString *year = [dateStr substringWithRange:NSMakeRange(0, 4)];
NSString *month = [dateStr substringWithRange:NSMakeRange(5, 2)];
NSString *day = [dateStr substringWithRange:NSMakeRange(dateStr.length-2, 2)];
NSLog(@"出生于%@年%@月%@日", year, month, day);
NSDate *nowDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
NSDateComponents *compomemts = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay fromDate:nowDate];
NSInteger nowYear = compomemts.year;
NSInteger nowMonth = compomemts.month;
NSInteger nowDay = compomemts.day;
NSLog(@"今天是%ld年%ld月%ld日", nowYear, nowMonth, nowDay);

// 计算年龄
NSInteger userAge = nowYear - year.intValue - 1;
if ((nowMonth > month.intValue) || (nowMonth == month.intValue && nowDay >= day.intValue)) {
userAge++;
}
NSLog(@"用户年龄是%ld",userAge);

你可能感兴趣的:(iOS 时间与时间戳相互转化以及基本应用)