user8154740
user8154740

Reputation: 39

In Objective-C how to get NSDate with milliseconds? dateFromString: method is ignoring milliseconds

I have used following code:

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];

Here value for str is correct with .milliseconds but when I try to convert this same string with same used datFormatter in NSDate, it returns NSdate without milliseconds.

Upvotes: 1

Views: 288

Answers (1)

Kuldeep Tanwar
Kuldeep Tanwar

Reputation: 3526

Use these functions and try to log the dates to get the accurate results :-

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

Upvotes: 1

Related Questions