【问题标题】:How to get Day number of week from NSDate如何从 NSDate 获取星期几
【发布时间】:2017-02-18 15:05:03
【问题描述】:

我想从 NSDate 知道星期几。

示例:- 假设今天是 2016 年 10 月 10 日,这里的周数是我使用的第 3 周

NSInteger week = [_calendar component:NSCalendarUnitWeekOfMonth fromDate:date];

现在我想知道本周的第几天,即 10 月 10 日的第 2 天。

【问题讨论】:

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

它会为您获取日期编号即2。每周的天数始终相同。 (1-7)。

正如 Vyachaslav Gerchicov 所指出的,工作日编号从星期日开始
星期日是 1,星期一是 2...星期六是 7

//Assuming your calendar is initiated like this
NSCalendar *_calendar = [NSCalendar currentCalendar];

//Fetch the day number
NSInteger day = [_calendar component:NSCalendarUnitWeekday fromDate:date];

探索NSCalendar了解更多详情here


对于 Swift 5.x

let day = Calendar.current.component(.weekday, from: date)

探索Calendar了解更多详情here

【讨论】:

  • 如果我一年中的某一天说第 111 天,我如何才能将其检索为 21-04-2018
  • 你忘了说星期天是 1 点。
  • @XcodianSolangi 我迟到了。但是如果你想做一些事情,比如从天数中检索日期。只需将日期设为 2018 年 1 月 1 日并添加 111 天。这将为您提供一个新的日期。探索 Calendar.current.date(byAdding...) 方法。如果您有兴趣,这里是链接。 stackoverflow.com/a/5067868/2545465
【解决方案2】:

使用这个

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitWeekday ) fromDate:[NSDate date] ];
NSNumber *weekNo = [NSNumber numberWithInteger:dateComponent. weekday];

【讨论】:

  • 它给出了一个天数?。我想它应该给出每年的周数
  • @RajanMaheshwari 它是返回年份周数。
  • 然后再阅读问题
  • 您是否尝试过打印变量weekNo 的值。只需打印一次并查看问题。我想它会给你最大 int 值而不是期望的结果
  • @RajanMaheshwari 请立即查看。
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 2016-10-22
  • 2017-11-07
  • 1970-01-01
相关资源
最近更新 更多