在Objective-C中如何获得NSDate毫秒? dateFromString:方法忽略毫秒

时间:2018-04-25 09:48:44

标签: objective-c date nsdate nsdateformatter

我使用了以下代码:

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转换这个相同的字符串时,它返回的NSdate没有毫秒。

1 个答案:

答案 0 :(得分:1)

使用这些功能并尝试记录日期以获得准确的结果: -

-(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;
}