简体   繁体   English

如何从NSString获取NSTimeInterval?

[英]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 . 我试图将以下字符串“2016-05-15T14:40:43.447”转换为NSDate但它不是NSDateFormatter总是返回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? 我已经检查过什么格式字符串我在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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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