gpt4 book ai didi

objective-c - 获得正确的 NSDate 值——这是最有效的方法吗?

转载 作者:行者123 更新时间:2023-11-29 13:42:39 24 4
gpt4 key购买 nike

我有这段代码可以获取本地日期/时间。它有效,但要获得我当前的日期/时间值而不是格林威治标准时间,似乎绕着灌木丛(10 个语句)走了很长一段路。

NSDate          *currentDateGMT = [NSDate date];
NSDateFormatter *currentDateDateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *currentDateTimeZoneGMT = [NSTimeZone timeZoneWithName:@"GMT"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[currentDateDateFormatter setTimeZone: currentDateTimeZoneGMT];
[currentDateDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
[currentDateDateFormatter setLocale:locale];

NSString *currentDateString = [currentDateDateFormatter stringFromDate:currentDateGMT];
NSDate *currentDateAdjusted = [currentDateDateFormatter dateFromString:currentDateString];

[currentDateDateFormatter release];

有人可以确认这是获取当前机器值的最佳方式吗?

谢谢

最佳答案

NSDateFormatter 将默认为用户时区,因此最简单的解决方案是

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//lower case h for hour will also default to the users
//12/24 hour clock preference
[formatter setDateFormat:@"yyyy-MM-dd hh:mm"];

NSString *currentDate = [formatter stringFromDate:[NSDate date]];

[formatter release];

关于objective-c - 获得正确的 NSDate 值——这是最有效的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8674115/

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