Objective-CでJSON日付(ティック)をNSDateに変換する方法を知っている人はいますか? 誰かがコードを投稿できますか?
4 に答える
ここで推測していますが、JSON値は1970年からのミリ秒数ですよね?NSDateのdateWithTimeIntervalSince1970:
メソッドを使用して、正しい時刻のNSDateオブジェクトを返すことができます。NSDateに渡す前に、必ずJSONミリ秒数を秒に変換してください。Cocoaはほとんどの場所でNSTimeIntervalを使用します。これは、秒単位の間隔を表します。
おおよそ次のようになります。
// 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];
それを行うには、クライアントのロケールを検出する必要があり、クライアントがその方法を知らない限り、おそらくあまり意味がありません。
NSDate の descriptionWithLocale: は、別のロケール用にフォーマットする方法です。また、timeIntervalSince1970 は 1970 年以降の (秒) に戻ります。これに 1000 を掛けると、ms がクライアントに返されます。それはすべてNSDateのドキュメントにあります。
このページによると: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspxティックは 0001 年 1 月 1 日に始まるため、dateWithTimeIntervalSince1970:
ティックで動作するように自動的に設定されません。この方法は引き続き使用できますが、違いを調整する必要があります。