NSDate与时间戳的那点事

对于项目中常常使用的时间来说,通过时间戳的形式进行数据的操作能带来极大的方便,以下就时间戳的生成和转换通过Demo的形式进行解说

声明一个时间类型的变量:

       // 获取当前的时间
        // 以下的第一个方法不提倡
        // NSDate *now1 = [[NSDate alloc]initWithTimeIntervalSinceNow:8*60*60];
        NSDate * today = [NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate:today];
        NSDate *localeDate = [today dateByAddingTimeInterval:interval];
        NSLog(@"%@", localeDate);
        // 时间转换成时间戳
        NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[localeDate timeIntervalSince1970]];
        NSLog(@"timeSp : %@", timeSp);

时间戳转换成时间类型(NSDate)

        // 时间戳转换成日期
        NSDate *currentTime = [NSDate dateWithTimeIntervalSince1970:[timeSp intValue]];
        NSLog(@"currentTime : %@", currentTime);



posted @ 2014-12-30 19:27  zfyouxi  阅读(539)  评论(0编辑  收藏  举报