NSString 日期转换为时间戳:
// 如格式为:### xxxx-xx-xx xx:xx:xx ### 我们应该怎样把NSString日期转换为时间戳呢
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:dateString];
NSTimeInterval interval = [date timeIntervalSince1970];
NSString *timeStamp = [NSString stringWithFormat:@"%i", (int)interval];
如果开发过程中后端返回上述格式的字符串,为 NSString 写个Category,方便初始化 model,如下:
@implementation NSString (NSDate)
- (NSDate *)dateWithFormat:(NSString *)format;{
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = format;
return [formatter dateFromString:self];
}
@end
self.field_name = [[[infoDict formateObjectForKey:@"field_name"] dateWithFormat:@"yyyy-MM-dd HH:mm:ss"] timeIntervalSince1970];
NSString 时间戳转换为 NSDate:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
NSString *str = [NSString stringWithFormat:@"%@",
[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[timeStamp integerValue]]]];