Stas
Stas

Reputation: 9935

Writing a proper timestamp for string date

I'm trying to obtain NSDate from the given string:

NSString* dateString = @"March 23 04:00 AM";
NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[firstDateFormatter setDateFormat:@"MMММ dd h:mm a"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[firstDateFormatter setLocale:locale];
NSDate* date = [firstDateFormatter dateFromString:dateString];
NSLog(@"date:%@", date);

The date I am getting is null where I've made a mistake?

Upvotes: 0

Views: 356

Answers (2)

Piotr Czapla
Piotr Czapla

Reputation: 26532

There is an issue with the date format you set. According to apple

The format string uses the format patterns from the Unicode Technical Standard #35

In your case you need to use stand-alone version of month that is LLLL not MMMM. If you change this line, your code will work just fine

[firstDateFormatter setDateFormat:@"LLLL dd hh:mm a"];

The standard explains the standalone version as follow:

The most important distinction to make between format and stand-alone forms is a grammatical distinction, for languages that require it. For example, many languages require that a month name without an associated day number be in the basic nominative form, while a month name with an associated day number should be in a different grammatical form: genitive, partitive, etc. Another common type of distinction between format and stand-alone involves capitalization; however, this can be controlled separately and more precisely using the element as described in Section 5.19 ContextTransform Elements.

Btw. Read this it contains a lot of info along with better ways of initializing the dateformatter.

Upvotes: 2

Evan Mulawski
Evan Mulawski

Reputation: 55334

Use hh for two-digit hours:

[firstDateFormatter setDateFormat:@"MMММ dd hh:mm a"];

Upvotes: 0

Related Questions