Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate from string

Tags:

ios

iphone

I have a string "2012-09-16 23:59:59 JST" I want to convert this date string into NSDate.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"];
NSLog(@"%@", capturedStartDate);

But it is not working. Its giving null value. Please help..

like image 506
NiKKi Avatar asked Sep 14 '12 06:09

NiKKi


People also ask

What is NSDate?

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

Is NSDateFormatter thread safe?

Thread Safety On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.

How do I get the current date in a string in Objective C?

Just 3 steps. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; Set the date format in which you want your string.


1 Answers

When using 24 hour time, the hours specifier needs to be a capital H like this:

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

Check here for the correct specifiers : http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

However, you need to set the locale for the date formatter:

// Set the locale as needed in the formatter (this example uses Japanese)
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]];

Full working code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]];
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"];
NSLog(@"Captured Date %@", [capturedStartDate description]);

Outputs (In GMT):

Captured Date 2012-09-16 14:59:59 +0000
like image 116
danielbeard Avatar answered Oct 12 '22 16:10

danielbeard