gpt4 book ai didi

ios - GMT 与夏令时更改的本地时间转换

转载 作者:行者123 更新时间:2023-11-29 10:52:53 33 4
gpt4 key购买 nike

我从服务器接收 GMT 时间结构(用户定义的结构),使用它我想将其转换为本地时间,我通过用接收到的结构填充 NSDatecomponent 来完成它,然后我使用日期格式化器来从中获取日期,除一种情况外,一切正常。如果 GMT 时间在 11 月 3 日之后(美国为 Daylight Saving Time 更改)格式化程序将产生 1 小时时差。

例如:如果预定时间为 11 月 3 日下午 4 点,则在从格林威治标准时间转换为本地时间后,将给出 11 月 3 日下午 3 点。

知道如何避免它。

编辑:

   // Selected Dates
NSDateComponents *sel_date = [[NSDateComponents alloc]init];
sel_date.second = sch_detail.sel_dates.seconds;
sel_date.minute = sch_detail.sel_dates.mins;

sel_date.hour = sch_detail.sel_dates.hours;
sel_date.day = sch_detail.sel_dates.date;
sel_date.month = sch_detail.sel_dates.month;
sel_date.year = sch_detail.sel_dates.year;
sel_date.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];



// Get the Date format.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

// Start_date formatter.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd, yyyy hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

NSDate *strt_date_loc = [gregorian dateFromComponents:sel_date];


// Get date string.
NSString *sel_date_time = [dateFormatter stringFromDate: strt_date_loc];+

sel_date_time 字符串比预期时间少一小时..

日志:

strt_date_loc = 2013-11-30 06:56:00 +0000

sel_date_time = 2013 年 11 月 29 日晚上 10:56(但应该是晚上 11:56)

时区:帕洛阿尔托(美国)

本地到 gmt 转换:

- (NSDateComponents*) convert_to_gmt_time : (NSDate*) date
{
NSDate *localDate = date;
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

NSDateComponents *date_comp = [[NSCalendar currentCalendar] components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:gmtDate];

return date_comp;
}

谢谢。

最佳答案

你的结果是正确的。日期格式化程序不使用当前 时差您本地时间和格林威治标准时间之间的时差,但在转换的日期。

夏令时在那个日期还没有生效,所以 UTC/GMT 和加州时间之间的时差是 8 小时。因此

2013-11-30 06:56:00 +0000 = 2013-11-29 22:56:00 -0800 = Nov 29, 2013 10:56 PM

这就是你得到的。

已添加:本地日期到 GMT 组件的转换无法正常工作因为

[[NSTimeZone defaultTimeZone] secondsFromGMT] 

是与 GMT 的当前时差,而不是有效的时差在要转换的日期。以下内容应该可以正常工作(甚至更短):

NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *date_comp = [cal components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:localDate];

关于ios - GMT 与夏令时更改的本地时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19675405/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com