zoukankan      html  css  js  c++  java
  • OC处理.Net Json时间格式

    通过服务器收到的json时间格式是/Date(xxxxxxxxxxxxx+xxxx)/,其中前半部分是自1970年的millionSecs,后半部是时区,我们需要对齐进行转换。

    解决方式有两种,第一种就是在服务端将时间转换为字符串再发送,那样在IOS端直接用NSDateFormater就能获得时间

    如果你对服务端没选择的话,就要自己转换了

    只要明白xxxxxxxxxxxxx+xxxx的格式的意义我们就有思路了

    首先通过正则表达式取出时间部分和时区部分,计算就可以了

    代码如下

    + (NSDate *)DateFromDotNetJSONString:(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;
    }
  • 相关阅读:
    DHCP DHCPv6
    DHCPv6协议
    IPv6邻居发现协议
    CentOS下禁止防火墙
    centOS下更新yum源
    centOS下yum报错
    Flink+Kafka整合的实例
    Flink基本概念
    Ubuntu16.04下配置ssh免密登录
    Zookeeper+Kafka的单节点配置
  • 原文地址:https://www.cnblogs.com/keithmoring/p/4161290.html
Copyright © 2011-2022 走看看