NSDateFormatter - 模拟器与硬件上的星期几不同

发布于 2024-10-28 13:07:40 字数 895 浏览 3 评论 0原文

我正在尝试确定我的应用程序中的当前日期。为此,我需要执行以下操作:

NSDateFormatter* dayDateFormatter = [[NSDateFormatter alloc] init];
[dayDateFormatter setDateFormat:@"e"];
int todayDayNum = [[dayDateFormatter stringFromDate:[NSDate date]] intValue];
[dayDateFormatter release];
NSLog(@"%d", todayDayNum);

今天对我来说目前是星期四,在我的 iPhone 上,我得到的结果是值 4。然而,在模拟器上我得到5

我做错了什么吗?我已尝试使用 ce 作为格式字符串。我还仔细检查了模拟器和设备上的日期/时间是否正确(并且相同)。

编辑:我已将代码更改为以下内容,现在似乎可以一致地工作(我的设备和模拟器都得到5。我猜测这是因为我的设备正在使用其他日历?

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:(NSWeekdayCalendarUnit) fromDate:[NSDate date]];
NSInteger todayDayNum = [weekdayComponents weekday];
NSLog(@"%d", todayDayNum);

I'm trying to determine the current day of the week in my app. To do this I have:

NSDateFormatter* dayDateFormatter = [[NSDateFormatter alloc] init];
[dayDateFormatter setDateFormat:@"e"];
int todayDayNum = [[dayDateFormatter stringFromDate:[NSDate date]] intValue];
[dayDateFormatter release];
NSLog(@"%d", todayDayNum);

Today is currently a Thursday for me, and on my iPhone I am getting the value 4 as the result. However, on the simulator I get 5.

Is there something I am doing wrong? I have tried both c and e as the format string. I have also double checked that the date/time is correct (and the same) on both the simulator and the device.

Edit: I've changed my code to the following, which seems to work consistently now (I get 5 for both my device and the simulator. I am guessing that this is because my device is using some other calendar?

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:(NSWeekdayCalendarUnit) fromDate:[NSDate date]];
NSInteger todayDayNum = [weekdayComponents weekday];
NSLog(@"%d", todayDayNum);

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

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

发布评论

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

评论(1

榕城若虚 2024-11-04 13:07:40

尝试玩
[公历 setFirstWeekday:1]; // 星期日 == 1,星期六 == 7 等

或区域设置 - [gregorian setLocale:[NSLocale currentLocale]];
因为它也影响了

try to play with
[gregorian setFirstWeekday:1]; // Sunday == 1, Saturday == 7 etc

or locale - [gregorian setLocale:[NSLocale currentLocale]];
because it influenced too

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