【问题标题】:An issue when I want to get Sunday of this week当我想得到本周的星期日时的一个问题
【发布时间】:2012-03-18 13:47:12
【问题描述】:

我编写这些代码是为了获得本周的星期日。

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents* components = [cal components: NSYearForWeekOfYearCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:[NSDate date]];

// I want to get the sunday
[components setWeekday:1];
NSDate* d = [cal dateFromComponents:components];
NSLog(@"Sunday:%@", d);

但我得到了结果:2012 年 2 月 25 日,我认为正确的结果应该是 2012 年 2 月 26 日。 它有什么问题?

【问题讨论】:

  • 哎呀,没关系,我在看三月。 :)
  • 也许NSMonthCalendarUnit 把它扔掉了?

标签: ios xcode nsdate nsdatecomponents


【解决方案1】:

你需要初始化更多的组件:

for (int i = 0; i < 12; i++)
{
    [components setWeek:i];
    [components setWeekday:1];
    d = [cal dateFromComponents:components];
    NSLog(@"Sunday,Week %d:%@", i,d);   
}

Output:

Sunday,Week 0:2011-12-25 08:00:00 +0000
Sunday,Week 1:2012-01-01 08:00:00 +0000
Sunday,Week 2:2012-01-08 08:00:00 +0000
Sunday,Week 3:2012-01-15 08:00:00 +0000
Sunday,Week 4:2012-01-22 08:00:00 +0000
Sunday,Week 5:2012-01-29 08:00:00 +0000
Sunday,Week 6:2012-02-05 08:00:00 +0000
Sunday,Week 7:2012-02-12 08:00:00 +0000
Sunday,Week 8:2012-02-19 08:00:00 +0000
Sunday,Week 9:2012-02-26 08:00:00 +0000
Sunday,Week 10:2012-03-04 08:00:00 +0000
Sunday,Week 11:2012-03-11 08:00:00 +0000

【讨论】:

  • 奇怪,使用你的代码,我的输出是:Sunday,Week 0:2011-12-24 16:00:00 +0000 Sunday,Week 1:2011-12-31 16:00:00 +0000 星期日,第 2 周:2012-01-07 16:00:00 +0000 星期日,第 3 周:2012-01-14 16:00:00 +0000 星期日,第 4 周:2012-01-21 16:00: 00 +0000 周日、周 5:2012-01-28 16:00:00 +0000 周日、周 6:2012-02-04 16:00:00 +0000 周日、周 7:2012-02-11 16:00 :00 +0000 星期日, 周 8:2012-02-18 16:00:00 +0000 星期日,周 9:2012-02-25 16:00:00 +0000 星期日,周 10:2012-03-03 16: 00:00 +0000 周日,周 11:2012-03-10 16:00:00 +0000
  • 这很奇怪。你在国际日期变更线的另一边吗? :)
猜你喜欢
  • 2012-11-27
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多