Maulik
Maulik

Reputation: 19418

Strange issue of Date from String

A Strange issue :

I am converting a String into the Date by following code :

NSString *dateStr = @"02/10/2012 12:00:13 PM";

NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
[dtF setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];

NSDate *d = [dtF dateFromString:dateStr];
NSDateFormatter *dateFormatStr = [[NSDateFormatter alloc] init];

[dateFormatStr setDateFormat:@"MMMM dd, yyyy HH:mm a"];
NSString *strDate = [dateFormatStr stringFromDate:d];   
NSLog(@"Output:::-->%@",strDate);

I am using Xcode 4.2

Its working fine in Simulator and in Device iPhone 3Gs and iPad with iOS 5.0 and iPhone 4

But the issue is in iPod with iOS 5.0.1. In iPod it shows (null) value.

What is wrong in code ? OR is there any other issue ?

Upvotes: 2

Views: 978

Answers (3)

Maulik
Maulik

Reputation: 19418

Solved !!!

The problem was in the date string NSString *dateStr = @"02/10/2012 12:00:13 PM";

The time is in 24hr format with "AM/PM" I think which was wrong. AM/PM should be with 12hr format.

So, I just removed AM/PM from string and it worked !!!

also from code :

[dtF setDateFormat:@"MM/dd/yyyy HH:mm:ss"];

Upvotes: 1

SomaMan
SomaMan

Reputation: 4164

I've found that NSDateFormatter output can be erratic due to users' settings on their iPhones. You can force it to be standardised (I can't remember the details) by using this -

[dtF setLocale:enUSPOSIXLocale];

...makes the whole output more predictable.

Upvotes: 3

Devang
Devang

Reputation: 11338

Rather then a try aaa

Replace your code with following :

NSString *dateStr = @"02/10/2012 12:00:13 PM";

NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
[dtF setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];

NSDate *d = [dtF dateFromString:dateStr];
NSDateFormatter *dateFormatStr = [[NSDateFormatter alloc] init];

[dateFormatStr setDateFormat:@"MMMM dd, yyyy hh:mm aaa"];
NSString *strDate = [dateFormatStr stringFromDate:d];   
NSLog(@"Output:::-->%@",strDate);

Output:::-->February 10, 2012 12:00 PM

Upvotes: 2

Related Questions