以毫秒為整數值的時間戳轉換
時間戳轉化為時間NSDate
代碼如下復制代碼
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
// 格式化時間
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
// 毫秒值轉化為秒
NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
NSString* dateString = [formatter stringFromDate:date];
returndateString;
}
時間轉化為時間戳
代碼如下復制代碼
// 當前時間
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[date timeIntervalSince1970]*1000;// *1000 是精確到毫秒,不乘就是精確到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", a];//轉為字符型
通過比較時間與當前時間返回年月日的方法
代碼如下復制代碼
- (void)getBabyDetailAge:(NSString *)date
{
// 獲得日期對象
NSDateFormatter *formatter_ = [[NSDateFormatter alloc] init];
formatter_.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createDate = [formatter_ dateFromString:date];
NSCalendar *gregorian = [[ NSCalendar alloc ] initWithCalendarIdentifier : NSCalendarIdentifierGregorian];
NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components = [gregorian components:unitFlags fromDate:createDate toDate:[NSDate date] options: 0 ];
NSInteger years = [components year];
NSInteger months = [components month ];
NSInteger days = [components day ];
}