ios - NSDateFormatter dateFromString 返回错误月份的日期

标签 ios xcode nsdateformatter

我有以下代码:

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

最佳答案

您的问题是您在几个月和几分钟内都在使用 m

代替

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

你必须使用:

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

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

对于 swift

formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

关于ios - NSDateFormatter dateFromString 返回错误月份的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726045/

相关文章:

ios - AVAudioPlayerNode 不播放声音

ios - viewControllers 在应用程序 didFinishLaunching *之前*初始化

ios - 在 iOS 中使用 Swift 发送短信

xcode - 为什么我的 info.plist 和 .pch 文件是红色的?

ios - 从 Xcode 导出的 XLIFF 文件中没有 <target>

ios - 生成这种类型的 NSDate : 2015-04-27T10:45:52Z

iphone - 同一 View 中的两个 uipicker

xcode - 如何知道在 xcode swift 中什么改变了变量值

ios - 在 SQLite 中存储 NSDate 在 GMT 中检索和显示显示,需要在创建时显示原始时区的时间

iphone - NSDateFormatter 无法正常工作?