获取正确的 NSDate 值 - 这是最有效的方法吗?

发布于 2024-12-23 07:20:04 字数 815 浏览 2 评论 0原文

我有这个代码来获取本地日期/时间。它有效,但要获取我当前的日期/时间值而不是 GMT 时间,似乎还有很长的路要走(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];

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

谢谢

I have this code to get the local date/time. It works but it seems a long way around the bush (10 statements) to get my current date/time value rather than the GMT time.

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];

Can someone confirm that this is the best way to obtain the current machine value?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仙女 2024-12-30 07:20:04

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];

NSDateFormatter will default to the users time zone so the simplest solution is

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文