Khant Thu Linn
Khant Thu Linn

Reputation: 6133

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.

Upvotes: 1

Views: 204

Answers (2)

Jon Rose
Jon Rose

Reputation: 8563

The library you are using is bad. There are other parameters that you need to set on the NSDateFormatter that are not being set and are using the system settings. Don't use DateTool just create your own NSDateFormatter. In addition to the timezone, and formatString you must also set the calendar and the locale.

see https://developer.apple.com/library/content/qa/qa1480/_index.html

Upvotes: 1

user7219266
user7219266

Reputation:

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 ?

Upvotes: 1

Related Questions