NSDateFormatter dateFromString Always Returns nil
There are two issues here:
The format of date string the formatter is expecting (
@"yyyy-MM-dd hh:mm:ss"
) is different from the format of the date string you're trying to parse (@"EEEE, MMMM d, yyyy 'at' h:mm:ss a zzzz"
).Setting the formatter's locale to
[NSLocale systemLocale]
is causing[dateFormat dateFromString:]
to returnnil
. Set it to[NSLocate currentLocale]
.
The full code for the formatter should be:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"EEEE, MMMM d, yyyy 'at' h:mm:ss a zzzz"];
[dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *date = [dateFormat dateFromString:dateString];
DateFormatter dateFromString Always Returns nil in swift 3
The forced unwrapping in
if let date : NSDate = (dateFormatter.date(from: dateString)! as NSDate) {
return date
}
makes the program crash if dateString
does not match the date format and dateFormatter.date(from: dateString)
returns nil
.
What you probably want is
if let date = dateFormatter.date(from: dateString) {
return date
}
or, if you really need an NSDate
and not a Date
:
if let date = dateFormatter.date(from: dateString) {
return date as NSDate
}
In addition, you might want to set the formatter's locate to "POSIX"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
in order to avoid a dependency on the user's regional preferences,
compare DateFormatter doesn't return date for "HH:mm:ss".
Swift date from string always returns nil
Your dateFormat
for Apr 25 2018 12:00AM
is not right. You are using M dd yyyy h:mm A
, but format would be MMM dd yyyy hh:mma
.
Use this link to check date format.
Code Should be:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMM dd yyyy hh:mma"
let SLAIssuedFinalGradingDate = formatter.date(from: tableDic["SLAIssuedFinalGradingDate"] as! String)
formatter.dateFormat = "yyyy-MM-dd"
let SLAIssuedFinalGradingDateString = formatter.string(from: SLAIssuedFinalGradingDate!)
Swift DateFormatter returns nil while converting String to Date
Your DateFormatter
expects the original string to be in the January, 18, 2018
format. You should convert it to a Date
first and only convert it to another format after that.
Also, you should not use YYYY
when referring to an ordinary calendar year. See this question for details.
let str = "2018-01-18 13:04:42 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
guard let date = dateFormatter.date(from: str) else {
return
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMMM, dd, yyyy"
let newStr = newDateFormatter.string(from: date)
print(newStr) /*January, 18, 2018*/
NSDateFormatter: dateFromString returns nil
set date format as
1996-08-09T07:00:00Z
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
update
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
[dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *date = [dateFormat dateFromString:@"1996-08-09T07:00:00Z"];
NSLog(@"date : %@", date);
[dateFormat setDateFormat:@"yyyy"];
NSString *finalStr = [dateFormat stringFromDate:date];
NSLog(@"finalStr : %@", finalStr);
output
NSDate dateFromString returns nil on Device Language Change
Going by the comments above, set the locale as follows
- (NSDate*) GetTime:(NSString*) txt
{
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
[df setDateFormat:@"hh:mm a"];
return [df dateFromString:txt];
}
This will ensure that no matter the devices locale, if you are passing it an english string for the time in the required format, it will properly create an NSDate
.
iOS - NSDateFormatter dateFromString returns nil only in one case
After a few comments, it has been determined that the code in the question is being run with the locale of es_PE
. This is the country of Peru. The date in question is January 1, 1990. By default, NSDateFormatter
uses the local timezone and when parsing date strings that have no time, midnight is assumed.
In Peru, in the year 1990, day light savings began at midnight, January 1st, 1990. This means that clocks went from December 31, 1989 at 11:59:59pm straight to January 1, 1990 at 1:00:00am. There was no midnight on January 1, 1990.
This is why the attempt to convert the string 01-01-1990
failed for this user. There was no midnight for this date in Peru (and possibly a few other locales, if any, that had day light saving start at the same time). Most people testing this code would claim it works just fine since most people testing this code don't live in Peru.
I found a useful website with helpful information. See http://www.timeanddate.com/time/change/peru/lima?year=1990 for details about Peru and day light savings time. Note that in 1989 and 1991, Peru did not use day light savings time.
stringFromDate always NIL
You need to convert your beginDate string to an actual NSDate first, and then do it:
NSString *beginDateString = [arr_data objectAtIndex:1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSZ"];
NSDate *beginDate = [formatter dateFromString:beginDateString];
[formatter setDateFormat:@"MMM dd hh:mm a"];
NSString *dateString = [formatter stringFromDate:beginDate];
NSLog(@"date: %@", dateString);
Note that you say in your question that you want it to output May 25 13:06 PM
but it will actually output May 25 01:06 PM
. (13:06 would be using 24 hour time instead of 12 hour time and wouldn't need the am/pm.)
Related Topics
How to Do Authorization and Login with Wechat Using the iOS Sdk
How to Call Https Url in Uiwebview
How to Change Tint Color of Uialertcontroller
Nsdata to Nsstring with JSON Response
Swift 3 - Alamofilre 4.0 Multipart Image Upload with Progress
iOS Unrecognized Selector Sent to Instance in Swift
Visually Modifying a Uitoolbar from Xcode Storyboard
Apple MACh-O Linker (Id) Warning:Building for MACosx, But Linking Against Dylib Built for iOS
Uitableviewcellaccessorycheckmark and Autolayout Constraints
Programmatically Highlight Uibarbuttonitem
Simple Uitableview in Swift - Unexpectedly Found Nil
Enable Uialertaction of Uialertcontroller Only After Input Is Validated
iOS 7 When Rotating View in Tab Bar, Right Side of View Is Not Clickable
Static VS Class as Class Variable/Method (Swift)
Disable iOS Simulator 'Connect Hardware Keyboard' Programmatically
How to Hide the Home Indicator with Swiftui
Errors Building Xcode Project After Adding in Run Script Fatal Error: Lipo: Input File