OStack程序员社区-中国程序员成长平台

标题: ios - 如何在 iOS 中解析 nsmutabledictionary 时间? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:36
标题: ios - 如何在 iOS 中解析 nsmutabledictionary 时间?

我已经使用以下代码解析了 Json

- (void) getWorkingCalendarNSData *)dataForParse{

    NSMutableArray *locations = [[NSMutableArray alloc] init];

    NSString* myString;
    myString = [[NSString alloc] initWithData:dataForParse encoding:NSASCIIStringEncoding];

    NSLog(@"data is %@", myString);

    NSArray * parsedData = [NSJSONSerialization JSONObjectWithData:dataForParse options:kNilOptions error:nil];

    NSLog(@"parser data %@", parsedData);


    for (NSDictionary *dict in parsedData) {


        NSLog(@"Value is %@", dict);

    }

    [delegate array:locations];


}

输出如下

2014-04-30 12:44:41.828 Testing[827:60b] parser data (
    "/Date(1399016682788+0400)/",
    "/Date(1399621482788+0400)/",
    "/Date(1400226282788+0400)/",
    "/Date(1400831082788+0400)/",
    "/Date(1401435882788+0400)/"
)
2014-04-30 12:44:41.829 Testing[827:60b] Value is /Date(1399016682788+0400)/
2014-04-30 12:44:41.829 Testing[827:60b] Value is /Date(1399621482788+0400)/
2014-04-30 12:44:41.829 Testing[827:60b] Value is /Date(1400226282788+0400)/
2014-04-30 12:44:41.830 Testing[827:60b] Value is /Date(1400831082788+0400)/
2014-04-30 12:44:41.830 Testing[827:60b] Value is /Date(1401435882788+0400)/
2014-04-30 12:44:41.830 Testing[827:60b] finishDownloading

如何从 NSDictionary 获取 NSString 中的时隙?

提前致谢。



Best Answer-推荐答案


您可能需要稍微调整一下,但这是我在这类日期中使用的:

头文件

@interface NSDate (JSON)

+ (NSDate *)dateFromJSONNSString *)dateString;

@end

实现

#import "NSDate+JSON.h"

@implementation NSDate (JSON)

+ (NSDate *)dateFromJSONNSString *)dateString {

    if (dateString == nil || [dateString isKindOfClass:[NSNull class]]) {
        return nil;
    }

    NSString *header = @"/Date(";
    NSRange headerRange = [dateString rangeOfString:header];
    if (headerRange.location != 0) {
        return nil;
    }

    NSString *footer = @")/";
    NSRange footerRange = [dateString rangeOfString:footer options:NSBackwardsSearch];
    if (footerRange.location == NSNotFound || footerRange.location + footerRange.length != dateString.length) {
        return nil;
    }

    NSString *timestampString = [dateString substringWithRange:NSMakeRange(headerRange.length, footerRange.location - headerRange.length)];

    NSTimeInterval interval = [timestampString doubleValue] * 0.001;
    return [NSDate dateWithTimeIntervalSince1970:interval];
}

@end

此示例不包括您日期中的时区,因此您可能需要添加该时区。

然后像这样使用它:

for (NSString *dateValue in parsedData) {
     NSDate *date = [NSDate dateFromJSON:dateValue];
}

关于ios - 如何在 iOS 中解析 nsmutabledictionary 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382544/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4