[英]NSDateFormatter dateFromString returns date with wrong month
I have the following code: 我有以下代码:
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];
}
Where I cycle through an array of dictionary objects - one of which is a date. 我在其中循环浏览字典对象的数组-其中一个是日期。 I have checked the format of the incoming date string - which is:
我检查了传入日期字符串的格式-这是:
2020-07-15 07:01:00 2020-07-15 07:01:00
However - once it has been through the dateformatter - the NSDate comes out as: 但是,一旦通过dateformatter,NSDate就会显示为:
2020-01-15 07:01:00 2020-01-15 07:01:00
Your problem is that you are using m
for both months and minutes. 您的问题是您在数月和数分钟内都使用了
m
。
Instead of 代替
[formatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
you have to use: 您必须使用:
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
Click here to see the full list of symbols you can use. 单击此处查看可以使用的符号的完整列表。
For Swift 对于斯威夫特
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.