gpt4 book ai didi

ios - 苹果手机日期格式

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:05:30 26 4
gpt4 key购买 nike

我试图格式化从 GMT+7GMT+3 的时间:

我正在构建一个带有特定国家/地区世界时钟的应用程序(用户将在 GMT+7 并且我想表示 GMT+3 时间)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setLocale:[NSLocale currentLocale];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
NSLocale *USLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:USLocale];
NSLog(@"Date for locale %@: %@",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);

我深入研究了 NSDate 类引用,但我不明白如何制作它。

如果有人能帮助我,我将不胜感激。

最佳答案

有 2 个重要的参数是分开工作的:时间和时区。

例如:越南使用 GMT+7

如果我知道越南时间是上午 9:00,那么 GMT 时间是凌晨 2:00。

当您从设备获取日期时,您将获取时间和时区:YYYY-MM-DD HH:MM:SS ±HHMM。其中 ±HHMM 是与 GMT 的时区偏移量,以小时和分钟为单位。

通常你只是在使用时间。但是,使用 NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"],您可以告诉 NSDateFormatter 您想要与本地时区相关的 GMT 时间。所以,与:

NSDateFormatter *dt = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
[dt setTimeZone:timeZone];

您可以获得本地时区日期的 GMT 日期。

所以,如果你有 GMT+7: 9:00 AM 并且你想打印出 GMT+3: 5:00 AM,你有 3 种可能性:

NSDate *localDate = [NSDate date];

选项 1

添加-4小时的时间间隔:

NSTimeInterval secondsInFourHours = -4 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInFourHours];
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:@"h:mm a"];
NSLog(@"GMT+7(-4) = %@", [dt stringFromDate:dateThreeHoursAhead]);

这是最简单的方法。如果您始终处于 GMT+7 并且需要 GMT+3,则这是 -4 小时的时间间隔。

选项 2

将时间设置为 GMT 时区,然后添加 +3 小时的时间间隔。最简单的方法是先加上 3 小时,然后将时间移至 GMT:

NSTimeInterval secondsInThreeHours = 3 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInThreeHours];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"h:mm a"];
NSString *date = [dateFormatter stringFromDate:dateThreeHoursAhead];
NSLog(@"GMT+3 = %@", date);

选项 3

这是更好的选择。 GMT+3 是 EAT(东非时间),您可以将时区设置为 EAT:[NSTimeZone timeZoneWithName:@"EAT"]

NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:@"h:mm a"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"EAT"];
[dt setTimeZone:timeZone];
NSLog(@"EAT = %@", [dt stringFromDate:localDate]);

选项 3 始终检索 GMT+3

An example code here .

关于ios - 苹果手机日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232193/

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