NSDateFormatter dateFromString返回错误月份的日期

问题描述 投票:0回答:1

我有以下代码:

for (i=0; i<json.count; i++) {

    NSDictionary *bodyDictionary = [json objectAtIndex:i];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:[bodyDictionary objectForKey:@"date"]];
    NSNumber* thisVolume = [NSNumber numberWithInteger:[[bodyDictionary objectForKey:@"volume"] integerValue]];

    NSTimeInterval timeNumber = [date timeIntervalSince1970];

    CGPoint point = CGPointMake(timeNumber, thisVolume.doubleValue);
    NSValue *pointValue = [NSValue valueWithCGPoint:point];
    [dataArray addObject:pointValue];

}

我循环遍历一个字典对象数组 - 其中一个是日期。我检查了传入日期字符串的格式 - 这是:

2020-07-15 07:01:00

然而 - 一旦它通过dateformatter - NSDate出现:

2020-01-15 07:01:00

ios xcode nsdateformatter
1个回答
3
投票

你的问题是你使用m几个月和几分钟。

代替

[formatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];

你必须使用:

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

单击here以查看可以使用的完整符号列表。

对于斯威夫特

formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
© www.soinside.com 2019 - 2024. All rights reserved.