Converting JSON date(ticks) to NSDate

后端 未结 4 1914
误落风尘
误落风尘 2021-01-21 08:34

Does anyone know how to convert a JSON date(ticks) to an NSDate in Objective-C? Can someone post some code?

4条回答
  •  旧巷少年郎
    2021-01-21 09:04

    It goes roughly like this:

    // Input string is something like: "/Date(1292851800000+0100)/" where
    // 1292851800000 is milliseconds since 1970 and +0100 is the timezone
    NSString *inputString = [item objectForKey:@"DateTimeSession"];
    
    // This will tell number of seconds to add according to your default timezone
    // Note: if you don't care about timezone changes, just delete/comment it out
    NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
    
    // A range of NSMakeRange(6, 10) will generate "1292851800" from "/Date(1292851800000+0100)/"
    // as in example above. We crop additional three zeros, because "dateWithTimeIntervalSince1970:"
    // wants seconds, not milliseconds; since 1 second is equal to 1000 milliseconds, this will work.
    // Note: if you don't care about timezone changes, just chop out "dateByAddingTimeInterval:offset" part
    NSDate *date = [[NSDate dateWithTimeIntervalSince1970:
                     [[inputString substringWithRange:NSMakeRange(6, 10)] intValue]]
                    dateByAddingTimeInterval:offset];
    

    (from https://gist.github.com/726910)

提交回复
热议问题