convert epoch time to NSDate in cocoa/iPhone

后端 未结 2 1124
失恋的感觉
失恋的感觉 2021-02-07 08:46

I have the value of the epoch time like say 123456789, now I want to convert this into NSDate in cocoa framework. Can anyone show me?

thanks

2条回答
  •  被撕碎了的回忆
    2021-02-07 08:55

    Since this is a high hit, going to contribute. Note that just converting to NSDate will put it into the UTC timezone. Then you have to convert over to your timezone if you want to display it to the user, from Convert epoch time to NSDate with good timezone with Objective c:

    // Convert NSString to NSTimeInterval
    NSTimeInterval seconds = [epochTime doubleValue];
    
    // (Step 1) Create NSDate object
    NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds];
    NSLog (@"Epoch time %@ equates to UTC %@", epochTime, epochNSDate);
    
    // (Step 2) Use NSDateFormatter to display epochNSDate in local time zone
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    NSLog (@"Epoch time %@ equates to %@", epochTime, [dateFormatter stringFromDate:epochNSDate]);
    
    // (Just for interest) Display your current time zone
    NSString *currentTimeZone = [[dateFormatter timeZone] abbreviation];
    NSLog (@"(Your local time zone is: %@)", currentTimeZone);
    

提交回复
热议问题