简体   繁体   中英

NSDate different in simulator and device(ipad)

Hi I am converting a GMT time to local time in my project - I getting the correct value in all simulator and in iPhone/iPod - but when I run this in iPad I am getting null, Here is my code -

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH:mm:ss";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
NSDate *startDate = [dateFormatter dateFromString:@"14:37:00"];  


NSLog(@"startDate---%@",startDate);

//This is startDate---2000-01-01 14:37:00 +0000 (in simulator/iPod/iphone)
 //  startDate---(null)  (in ipad)

Issue is with user's ipad's time format - if it is in 12 hour format - then the above code results null What do I do for this issue ??

bacause you time format is set to 12 hours on ipad device, the date string is in 24 hours format look at string @"14:37:00".

use

dateFormatter.dateFormat = @"hh:mm:ss";
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

Reference

if you want to force it to 12-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale to en_US_POSIX.

Use hh instead of HH.

hh usually is 12 hour time while HH is usually 24 hour time.

A good official reference for this, as linked by Apple themselves , is here . Another good table is here , as mentioned by Zaph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM