Converting JSON date(ticks) to NSDate

后端 未结 4 1858
误落风尘
误落风尘 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)

    0 讨论(0)
  • 2021-01-21 09:07

    You'd have to detect the client's locale in order to be able to do that, and unless your client knows how to do that, there's probably not much point.

    NSDate's descriptionWithLocale: would be the way you format it for another locale. And timeIntervalSince1970 will go back to the (seconds) since 1970, which you could multiply by 1000 to get ms to return to the client. It's all in the NSDate documentation.

    http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

    0 讨论(0)
  • 2021-01-21 09:10

    According to this page: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx ticks begin on Jan 1, 0001 so dateWithTimeIntervalSince1970: is not automatically setup to work with ticks. You can still use this method but should adjust for the difference.

    0 讨论(0)
  • 2021-01-21 09:16

    I'm guessing here but your JSON value is the number of milliseconds since 1970, right? You can use NSDate's dateWithTimeIntervalSince1970: method to return an NSDate object with the correct time. Just make sure to convert the JSON milliseconds number to seconds before passing it to NSDate-- Cocoa uses NSTimeInterval in most places, which represents an interval in seconds.

    0 讨论(0)
提交回复
热议问题