将日期从时区转换为设备本地时区和日期

 手机用户2502922477 发布于 2023-02-04 18:53

如何将timezone1的日期转换为设备本地时区2的日期?

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Jerusalem"]];
NSDate *date = [dateFormat dateFromString:timestamp];

then something like:
[dateFormat2 setTimeZone:[NSTimeZone localTimeZone]];
date2 = [dateFormat2 dateFromDate:date withOtherTimeZone:zone];

更新:

我想我明白了.

//get source date from the server
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate *sourceDate = [dateFormat dateFromString:timestamp];

//set timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Jerusalem"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

//calc time difference
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

//set current real date
NSDate* date = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

好吗?

1 个回答
  • 好先关,时间到了.在这第二个,地球上的任何地方,它都是同一秒.不要再考虑时间格式了.不是.所有时间都应该是GMT,然后您可以基于TimeZone显示它.

    Date *d = [NSDate date] ;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss Z"];
    NSTimeZone *nyTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"sometimeabbr."];
    NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
    [df setTimezone: nyTimeZone];
    NSLog(@"ny time is %@" , [df stringFromDate: d]);
    [df setTimeZone: localTimeZone];
    NSLog(@"local time is %@" , [df stringFromDate: d]);
    

    如果给定一个字符串日期并需要转换,请创建NSDateFormatter以摄取字符串日期.确保设置时区.现在你有一个NSDate对象(在NSDates中没有时区),你可以格式化成你想要的任何其他时区.

    请为所有神圣的爱所有.将时间视为前进的秒数,将时区视为这些时区的格式.

    2023-02-04 18:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有