从DataContractJsonSerializer格式化到iOS的日期

时间:2012-07-02 14:15:02

标签: c# iphone .net objective-c ios

我从json文件收到以下格式的日期。我不确定,但我认为它是由.Net框架中的DataContractJsonSerializer类格式化的。日期看起来像这样

    \/Date(1255993200000+0100)\/

我想知道是否有人会知道如何将此转换为iOS上的正常日期,或者如果我必须做任何事情来改变它。

谢谢,

1 个答案:

答案 0 :(得分:6)

试试这个

-(NSDate*)mfDateFromDotNetJSONString:(NSString *)string
{
    static NSRegularExpression *dateRegEx = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateRegEx = [[NSRegularExpression alloc] initWithPattern:@"^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    NSTextCheckingResult *regexResult = [dateRegEx firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];

    if (regexResult)
    {
        // milliseconds
        NSTimeInterval seconds = [[string substringWithRange:[regexResult rangeAtIndex:1]] doubleValue] / 1000.0;
        // timezone offset
        if ([regexResult rangeAtIndex:2].location != NSNotFound) {
            NSString *sign = [string substringWithRange:[regexResult rangeAtIndex:2]];
            // hours
            seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:3]]] doubleValue] * 60.0 * 60.0;
            // minutes
            seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:4]]] doubleValue] * 60.0;
        }

        return [NSDate dateWithTimeIntervalSince1970:seconds];
    }
    return nil;
}

并使用

传递字符串

[NSString stringWithFormat:...]此功能

这对我有帮助,并希望它可以帮助你