You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

dateFromString返回nil求助:NSString转NSDate函数异常排查

Fixing NSDateFormatter Returning nil for Your Date String

Hey there! Let's figure out why your function is returning nil—it's a common date formatting issue with two easy fixes.

The Core Problems

  1. Mismatched Date Format String
    Your input date string is "27-Mar-2018 18:28:09"—note the month is an English abbreviation (Mar). But you're using the format string dd-MM-yyyy HH:mm:ss, where MM stands for numeric months (like 03). To match the English month abbreviation, you need to use MMM instead of MM.

  2. Locale Misconfiguration
    Even with the right format string, NSDateFormatter might fail if your device's default locale doesn't recognize English month abbreviations (e.g., if the system is set to Chinese or another non-English locale). Using the en_US_POSIX locale fixes this—it's a fixed, locale-agnostic setting perfect for parsing standardized date strings.

Corrected Code

Here's your updated function with both fixes applied:

+ (NSDate *)getNSDateFromString:(NSString *)strDate andFormat:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // Set a consistent locale to avoid region-based parsing issues
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [formatter setDateFormat:format];
    NSDate *dateTime = [formatter dateFromString:strDate];
    return dateTime;
}

How to Call It Correctly

When passing your date string "27-Mar-2018 18:28:09", use this format string instead of your original one:

NSDate *date = [YourClass getNSDateFromString:@"27-Mar-2018 18:28:09" andFormat:@"dd-MMM-yyyy HH:mm:ss"];

Quick Debug Tip

If you run into similar issues later, you can reverse-engineer the correct format: create an NSDate and use stringFromDate with your format to see what output it generates. Compare that to your input string to spot mismatches instantly.

内容的提问来源于stack exchange,提问作者Nyein Ei Ei Tun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:19:21