Objective-C 如何获取毫秒级的NSDate? dateFromString:方法忽略毫秒
In Objective-C how to get NSDate with milliseconds? dateFromString: method is ignoring milliseconds
我使用了以下代码:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSDate *dateToday = [dateFormatter dateFromString:str];
此处 str 的值对于 .milliseconds 是正确的,但是当我尝试在 NSDate 中使用相同的 datFormatter 转换同一个字符串时,它 returns NSdate 没有毫秒。
使用这些函数并尝试记录日期以获得准确的结果:-
-(NSString *)stringFromDate:(NSDate *)date{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Date : %@",str);
return str;
}
-(NSDate *)dateFromString:(NSString *)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSDate *date=[dateFormatter dateFromString:dateString];
NSLog(@"Date : %@",[dateFormatter stringFromDate:date]);
return date;
}
我使用了以下代码:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSDate *dateToday = [dateFormatter dateFromString:str];
此处 str 的值对于 .milliseconds 是正确的,但是当我尝试在 NSDate 中使用相同的 datFormatter 转换同一个字符串时,它 returns NSdate 没有毫秒。
使用这些函数并尝试记录日期以获得准确的结果:-
-(NSString *)stringFromDate:(NSDate *)date{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Date : %@",str);
return str;
}
-(NSDate *)dateFromString:(NSString *)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSDate *date=[dateFormatter dateFromString:dateString];
NSLog(@"Date : %@",[dateFormatter stringFromDate:date]);
return date;
}