简体   繁体   English

dateFromString返回nil

[英]dateFromString returning nil

I have a function to convert NSString to NSDate. 我有一个将NSString转换为NSDate的函数。

+ (NSDate *)getNSDateFromString:(NSString *)strDate andFormat:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : format];
    NSString *stringTime = strDate;
    NSDate *dateTime = [formatter dateFromString:stringTime];
    return dateTime;
}

The value of strDate is "27-Mar-2018 18:28:09". strDate的值为“ 27-Mar-2018 18:28:09”。 The format is "dd-MM-yyyy HH:mm:ss" 格式为“ dd-MM-yyyy HH:mm:ss”

That function is returning nil value. 该函数返回nil值。 Can anyone help on this please. 任何人都可以帮忙。 Thanks. 谢谢。

Change date format to dd-MMM-yyyy HH:mm:ss 将日期格式更改为dd-MMM-yyyy HH:mm:ss

Here are nice references to understand date format string: Quick Guide to Objective-C DateFormatting & Date_Field_Symbol_Table 这是理解日期格式字符串的不错参考: Objective-C DateFormattingDate_Field_Symbol_Table 快速指南

y = year
Q = quarter
M = month
w = week of year
W = week of month
d = day of the month
D = day of year
E = day of week
a = period (AM or PM)
h = hour (1-12)
H = hour (0-23)
m = minute
s = second

If you match this with your date components 如果您将其与日期组件匹配

27-Mar-2018 18:28:09 = dd-MMM-yyyy HH:mm:ss

Where 哪里

27   = dd (date day)
Mar  = MMM (Month)
2018 = yyyy (year)
18   = HH (HH - 24 hours format and hh - 12 hours format)
28   = mm (minutes)
09   = ss (seconds)

As your date string is "27-Mar-2018 18:28:09". 由于您的日期字符串是“ 27-Mar-2018 18:28:09”。 The format should be "dd-MMM-yyyy HH:mm:ss". 格式应为“ dd-MMM-yyyy HH:mm:ss”。

Change the format from "dd-MM-yyyy HH:mm:ss" to "dd-MMM-yyyy HH:mm:ss" 将格式从"dd-MM-yyyy HH:mm:ss"更改为"dd-MMM-yyyy HH:mm:ss"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM