如何在Objective-C中将DateFormatter更改为timeStamp?

时间:2016-10-21 01:54:15

标签: objective-c timestamp

例如,我想将NSDateFormatter对象更改为“YYYY-MM-dd HH:mm”到时间戳,是否有人有好主意?

2 个答案:

答案 0 :(得分:0)

首先将日期字符串转换为NSDate,然后使用timeIntervalSince1970获取时间戳。

NSString *dateString = @"2016-10-12 10:30";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

NSDate *formattedDate = [inputFormatter dateFromString: dateString];

NSTimeInterval timestamp = [formattedDate timeIntervalSince1970];

答案 1 :(得分:0)

使用timeIntervalSince1970。试试吧:

NSString *mydateString = @"2010-7-5 1:39";
NSDateFormatter *Df = [[NSDateFormatter alloc] init];
[Df setDateFormat:@"yyyy-MM-dd HH:mm"];
[Df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];   

NSDate *formattedDate = [Df dateFromString: mydateString];

NSTimeInterval mYtimestamp = [formattedDate timeIntervalSince1970];

NSLog(@"Hello my time: %f--",mYtimestamp);
// To get it back:
NSTimeInterval _interval=mYtimestamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *dateString = [formatter stringFromDate:date];

NSLog(@"date again-:%@",dateString);