Ios 是否将utc日期转换为12小时本地日期?
我的日期和时间是2019年11月20日21:09,采用UTC 24小时格式。现在我想把它转换成当地时间,格式为12小时。2019年11月30日上午8:00像这样 我的代码是:Ios 是否将utc日期转换为12小时本地日期?,ios,objective-c,cocoa-touch,nsdate,nsdateformatter,Ios,Objective C,Cocoa Touch,Nsdate,Nsdateformatter,我的日期和时间是2019年11月20日21:09,采用UTC 24小时格式。现在我想把它转换成当地时间,格式为12小时。2019年11月30日上午8:00像这样 我的代码是: // create dateFormatter with UTC time format NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm"];
// create dateFormatter with UTC time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// change to a readable time format and change to local time zone
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];
当我将本地时间12格式转换为24小时UTC时的代码
-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
// NSLog(@"%@", localDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm"];
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.locale = twelveHourLocale;
NSTimeInterval timeZoneoffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval utcTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneoffset;
NSDate *utcCurrentDate = [NSDate dateWithTimeIntervalSinceReferenceDate:utcTimeInterval];
NSString *dateString = [dateFormatter stringFromDate:utcCurrentDate];
// NSLog(@"dateString %@", dateString);
return dateString;
}
-(NSDate *)getUTCDate:(NSString *)currentDate{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MMM-yyyy HH:mm"];
NSDate *date1 = [dateFormat dateFromString:currentDate];
if (date1 == nil){
[dateFormat setDateFormat:@"dd-MMM-yyyy hh:mm a"];
date1 = [dateFormat dateFromString:currentDate];
}
return date1;
}
我觉得你做得太多了。格式“hh”是12小时格式中的小时,hh是24小时格式。您不必为此设置语言环境(尽管设置为en_US_POSIX确实避免了用户在[NSLocale currentLocale]实例中的24小时首选项,这可以在iOS上覆盖该首选项) NSDate是时间上的绝对实例。您需要使用NSDateFormatter应用日历和时区,以从中获取数字年/月/日等值,但不需要调整参考日期的偏移量(即更改实际日期,而不仅仅是在不同时区中重新格式化)
问题是什么?它没有转换成本地12小时UTC时间@SGDev我编辑了我的代码请看。看一看
NSString *utcString = @"20-Nov-2019 21:09";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"dd-MMM-yyyy HH:mm";
NSDate *date = [formatter dateFromString:utcString];
formatter.timeZone = [NSTimeZone localTimeZone]; // GMT-5 for me
formatter.dateFormat = @"dd-MMM-yyyy hh:mm a";
NSLog(@"date: %@", [formatter stringFromDate:date]);
// date: 20-Nov-2019 04:09 PM