kee23
kee23

Reputation: 148

How do I convert a string that contains "am/pm" to an NSDate when the user's device is set to 24-Hour Time in iOS?

I need to convert an NSString to an NSDate, but the following code only works as long as the user's device isn't set to 24-Hour time.

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

NSString *aTime = @"2/11/2013 12:00:00 AM";
NSDate *aDate = [formatter dateFromString:aTime];

However, aDate returns null when the device is in 24-Hour time. Any help?

Upvotes: 2

Views: 1377

Answers (3)

Suhas Arvind Patil
Suhas Arvind Patil

Reputation: 1750

try this code

NSString *string = @"2015-11-30 15:00:00";
NSDateFormatter* formatter =  [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [formatter dateFromString:string];

date: 2015-11-29 21:30:00 +0000

its in UTC format you can modify this as you need!

Upvotes: 0

Mahesh Dhumpeti
Mahesh Dhumpeti

Reputation: 11

    I think the following snippet might helps you out.

    NSString *dateString = @"09:34 AM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"dd-MM-yyyy";
    NSString *stringFromDate = [dateFormatter stringFromDate:[NSDate date]];

    dateFormatter.dateFormat = @"dd-MM-yyyy hh:mm a";
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

    NSDate *returnDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", stringFromDate, dateString]];

Upvotes: 1

Tommy
Tommy

Reputation: 100632

I think you're probably seeing a side effect of the behaviour described by QA1480. Apple has resolved what it presumably thought was developers not obeying locales properly by modifying your prescribed date format unless you explicitly say not to.

You can achieve that by adding:

formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
      /* and autorelease if not using ARC */

Which basically says 'the date format I just set is explicitly what I want, please don't modify it in any way'.

Upvotes: 8

Related Questions