Display current time in epoch

喜欢而已 提交于 2019-12-25 19:03:15

问题


I'm trying to display the current time in epoch, i'm not sure if this is correct, but i'm sure it's not since it's giving me an error:

NSDate *currentDate = [NSDate date];
NSDate *epochDate = [NSDate dateWithTimeIntervalSince1970:currentDate];

Any idea of how to accomplish this?


回答1:


NSString *epochTime = @"1347522689";
NSTimeInterval epochInterval = [epochTime longLongValue];
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:epochInterval];
NSDateFormatter *dateFormatterEpoch = [[NSDateFormatter alloc] init];
[dateFormatterEpoch setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSString *epochDate = [dateFormatterEpoch stringFromDate:epochNSDate];

NSDate *currentDateNSDate = [NSDate date];
NSDateFormatter *dateFormatterCurrent = [[NSDateFormatter alloc] init];
[dateFormatterCurrent setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSString *currentDate = [dateFormatterCurrent stringFromDate:currentDateNSDate];


NSLog(@"epochDate = %@",epochDate);
NSLog(@"currentDate = %@", currentDate);

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags fromDate:epochNSDate toDate:currentDateNSDate options:0];

NSInteger year = [components month];
NSInteger months = [components month];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger min = [components minute];
NSInteger sec = [components second];


NSLog(@"Year Difference = %@\n Month Difference = %@\n, Days Difference = %@\n, Hours Difference = %@\n ,Minutes Difference = %@\n second Difference = %@\n", [[NSNumber numberWithInteger:year] stringValue] ,[[NSNumber numberWithInteger:months] stringValue], [[NSNumber numberWithInteger:days] stringValue], [[NSNumber numberWithInteger:hours] stringValue], [[NSNumber numberWithInteger:min] stringValue],[[NSNumber numberWithInteger:sec] stringValue]);



回答2:


NSTimeInterval epoch = [[NSDate date] timeIntervalSince1970];
NSLog(@"%f", epoch);

Or better yet, this gives just the integer part of the time:

int epoch = round([[NSDate date] timeIntervalSince1970]);
NSLog(@"%d", epoch);



回答3:


For converting your date to epoch. you need to use dateWithTimeIntervalSince1970 method like this below

NSDate *date = [NSDate date];
NSLog(@"epochDate: %f",([date timeIntervalSince1970]);


来源:https://stackoverflow.com/questions/22885867/display-current-time-in-epoch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!