带NSDate的偏移量的JSON日期 [英] JSON date with offset to NSDate
问题描述
我正在开发一个Cocoa应用程序在Mac上,我消耗一个WCF服务,它返回一个JSON日期,来自一个SQL Server DATETIMEOFFSET字段。从包含日期字段的服务返回的JSON对象如下所示:
I am developing an Cocoa application on the Mac and I am consuming a WCF service which is returning me a JSON date which comes from a SQL Server DATETIMEOFFSET field. The JSON object returned from the service including the date fields is outlined below:
{
"ObjectId": 1,
"Name": "My Object Name",
"Description": "My Object Description",
"CreateDate": {
"DateTime": "/Date(1306481778297)/",
"OffsetMinutes": 0
},
"LastModifiedDate": {
"DateTime": "/Date(1306936930427)/",
"OffsetMinutes": 0
}
}
我的问题是如何转换CreateDate和LastModifiedDate字段到NSDate对象?
My question is how do I convert the CreateDate and LastModifiedDate fields to NSDate objects?
我试图创建一个NSDateFormatter并以这种方式抽象值。但是,这适用于简单字符串日期或标准JSON日期(/ Date(1306936930427)/),但不适用于包含日期和偏移量的日期对象。
I attempted to create a NSDateFormatter and abstract the value that way. However this works for simple string dates or the standard JSON date (/Date(1306936930427)/) but not the the date object containing the date and the offset.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]
NSString *creationDate = [myObject valueForKey:@"CreateDate"];
NSDate *date = [dateFormatter dateFromString:creationDate];
任何对此的帮助都将非常感激。
Any help on this one will be much appreciated.
推荐答案
首先,从字符串中提取数字(例如1306936930427); NSScanner 可能派上用场。然后除以1000.0,并使用NSDate的 dateWithTimeIntervalSince1970:
类方法来获取你的NSDate。
First, extract the number from the string (e.g. 1306936930427); NSScanner might come in handy for this. Then divide it by 1000.0 and use NSDate's dateWithTimeIntervalSince1970:
class method to get your NSDate.
这篇关于带NSDate的偏移量的JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!