iOS 時間與時間戳相互轉(zhuǎn)化以及基本應(yīng)用(年齡計算,多久之前,有效期...)

一、時間戳與標準時間之間的相互轉(zhuǎn)化

1.獲取標準時間

  //獲取系統(tǒng)時間
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  //獲取系統(tǒng)時區(qū) **此時不設(shè)置時區(qū)是默認為系統(tǒng)時區(qū)
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.標準時間轉(zhuǎn)化時間戳

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.時間戳轉(zhuǎn)化成標準時間

  //時間戳轉(zhuǎn)化成時間
NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
[stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
  //以 1970/01/01 GMT為基準,然后過了secs秒的時間
NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:1485159493];
NSLog(@"時間戳轉(zhuǎn)化時間 >>> %@",[stampFormatter stringFromDate:stampDate]);

擴展

  //以 2001/01/01 GMT為基準,然后過了secs秒的時間
NSDate *stampDate = [NSDate dateWithTimeIntervalSinceReferenceDate:506852179];
  //以 現(xiàn)在的時間 GMT為基準,然后過了secs秒的時間
NSDate *stampDate3 = [NSDate dateWithTimeIntervalSinceNow:7*24*3600];
NSLog(@"時間戳轉(zhuǎn)化時間2 >>> %@",[stampFormatter stringFromDate:stampDate2]);
NSLog(@"時間戳轉(zhuǎn)化時間3 >>> %@",[stampFormatter stringFromDate:stampDate3]);

二、分別根據(jù)時間戳與標準時間計算: 幾分鐘之前,幾小時之前...

調(diào)用該方法,傳入后臺返回的時間戳

- (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:可以簡單且有效的獲取某個時間點對應(yīng)的“年”,“月”,“日”,“周”,“時”,“分”,“秒”等信息;還可以表示時間段,例如:一周,一個月,10年,5天,10分鐘,10秒等等。

- (void)getMondayAndSunday{
    
    NSDate *nowDate = [NSDate date];
    //先創(chuàng)建一個 遵循某個歷法 日歷對象
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierISO8601];
    NSDateComponents *compomemts = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay   fromDate:nowDate];
    // 獲取今天是周幾 (iOS規(guī)定的)星期天是1 星期一是2
    NSInteger weekday = compomemts.weekday;
    // 獲取今天是幾號
    NSInteger day = compomemts.day;
    NSLog(@"weekday:%ld \t day:%ld",weekday,day);
    
    // 計算當前日期分別于 周一和周天 的相差天數(shù)
    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);
    
    // 在當前日期(去掉時分秒)基礎(chǔ)上加上差的天數(shù)
    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);
}

四、計算星座

調(diào)用此方法,傳入?yún)?shù)格式為: 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];
    }
    
    //計算天數(shù)
    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];
}

五、根據(jù)生日計算年齡

根據(jù)出生日期計算年齡會經(jīng)常用到,我開始想用時間戳的方法來解決,簡單快速,但是這樣并不正確,因為沒有考慮到閏年的情況。所以這樣實現(xiàn)是不嚴謹?shù)摹?/strong>

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);

** 聲明**
本文如果有哪個地方有問題,希望大家可以提出來,我們共同討論。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 一、時間戳與標準時間之間的相互轉(zhuǎn)化1.獲取標準時間 2.獲取時間戳 3.標準時間轉(zhuǎn)化時間戳 4.時間戳轉(zhuǎn)化成標準時...
    摸摸頭發(fā)閱讀 1,504評論 0 2
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,789評論 25 709
  • 學(xué)習(xí)一定要學(xué)到最根本的那層?xùn)|西,即底層思維。 這是這段時間來我感受最為深刻的一條法則。 比如你有了點錢想學(xué)富人一樣...
    boxgirl閱讀 1,254評論 0 5
  • 只能自己理了,芳和師傅自己都是亂的。 先來計算成本,時間成本和金錢成本,關(guān)鍵是時間。除了跳舞之外,吃飯不行,出游估...
    行一館閱讀 199評論 0 0

友情鏈接更多精彩內(nèi)容