简体   繁体   中英

How to get NSTimeInterval from NSString?

I am trying to convert following string "2016-05-15T14:40:43.447" to NSDate but its not NSDateFormatter always returns nil .

This is what I'm doing currently.

- (NSTimeInterval) timeIntervalFromDateString:(NSString *)stringDate {
    if(!stringDate || ![stringDate length]) {
        return 0.0f;
    }
    static NSDateFormatter *df = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        df = [NSDateFormatter new];
        [df setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss.SSS"];
    });
    NSDate *date = [df dateFromString:stringDate];
    // date is always returns nil.
    return [date timeIntervalSince1970];
}

I have tried setting following formats:

yyyy-MM-dd'T'hh:mm:ss.SSS
yyyy-MM-dd'T'hh:mm:ssz
yyyy-MM-dd'T'hh:mm:ss Z
yyyy-MM-dd'T'hh:mm:ss.SSS Z
yyyy-MM-dd'T'hh:mm:ss.SSS z

But none of them worked.

I have checked What format string do I use for milliseconds in date strings on iPhone? as well, but doesn't help.

Any luck?

14:40:43是24小时格式,即大写14:40:43 H.

yyyy-MM-dd'T'HH:mm:ss.SSS

Try this code

- (NSTimeInterval) timeIntervalFromDateString:(NSString *)stringDate {
        if(!stringDate || ![stringDate length]) {
            return 0.0f;
        }
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.timeZone = [NSTimeZone localTimeZone];
        df.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
        NSDate *date = [df dateFromString:stringDate];

        return [date timeIntervalSince1970];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM