NSDateFormatter - 模拟器与硬件上的星期几不同
我正在尝试确定我的应用程序中的当前日期。为此,我需要执行以下操作:
NSDateFormatter* dayDateFormatter = [[NSDateFormatter alloc] init];
[dayDateFormatter setDateFormat:@"e"];
int todayDayNum = [[dayDateFormatter stringFromDate:[NSDate date]] intValue];
[dayDateFormatter release];
NSLog(@"%d", todayDayNum);
今天对我来说目前是星期四,在我的 iPhone 上,我得到的结果是值 4
。然而,在模拟器上我得到5
。
我做错了什么吗?我已尝试使用 c
和 e
作为格式字符串。我还仔细检查了模拟器和设备上的日期/时间是否正确(并且相同)。
编辑:我已将代码更改为以下内容,现在似乎可以一致地工作(我的设备和模拟器都得到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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试玩
[公历 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