Khant Thu Linn Khant Thu Linn -4 years ago 187
iOS Question

iOS converting date string with am, pm to NSDate (Device setting with 24 hour format)

I have date time string like this.


20 Feb 2017 03:32PM //This time is singapore time. So I need to choose singapore time zone


And I try to convert to NSDate like this.

NSDate *redeemDate = [NSDate dateWithString:currentDateString formatString:@"dd MMM yyyy hh:mma" timeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];


I use this library though. But it is also same if I manually format.
https://github.com/MatthewYork/DateTools

If device use 12 hour format, it is okay but if it use 24 hour format, I got nil. May I know why? I thought may be it is because of hh and I change to HH. But it is also not okay.

Answer Source

HH:mm => will look like 00:12, 23:00... this has 24 hour format.

hh:mm => will look like 01:00Am, 02:00Am,...01:00pm this has 12 hour format.

So you have to convert to the appropriate format if you want to display in an other time/date format.

Have a look here http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns

Example:

NSDate *date = [NSDate new];
NSString* format = @"dd MMM yyyy hh:mma'Z'";

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"SGT"];

[dateFormat setDateFormat:format];
[dateFormat setCalendar: calendar];

NSDate* formatDate = [dateFormat dateFromString:[dateFormat stringFromDate:date]];

Can you try this ?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download