【问题标题】:iPhone - how may I check if a date is Monday?iPhone - 我如何检查日期是否是星期一?
【发布时间】:2011-06-13 21:05:14
【问题描述】:

我正在尝试查找日期是否为星期一。

为此,我这样做:

#define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// for test and debug purpose
NSDateComponents* b = [calendar components:kDateAndHourUnitsComponents fromDate:retDate];
int a=[[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday];
// -----------

if ([[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday] == EKMonday) DoThis....

但这不起作用……a和b不包含任何有用的东西(a等于2147483647),

我也想知道 [calendar components:NSWeekdayCalendarUnit fromDate:retDate] 在这种情况下不再有用的用途......

我还发现这证实了这个过程: How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

我错过了什么?

【问题讨论】:

  • 在括号中包含宏定义总是一个好主意。像这样:#define kDateAndHourUnitsComponents (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)。否则很容易引入一些非常讨厌的难以发现的问题。
  • 好的,但是这些总是以这种方式使用,没有括号

标签: iphone compare nsdate dayofweek weekday


【解决方案1】:

你去吧,这有效并通过整数返回天数:7 = Sat,1 = Sun,2 = Mon...

目标 C

NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];

SWIFT 4.2

建立你想要检查星期几的日期

let dateComponents = DateComponents(
    year: 2019,
    month: 2 /*FEB*/,
    day: 23 /*23rd day of that month */
)

获取当前日历。

let cal = Calendar.current

现在使用日历检查构建日期是否为有效日期

guard let date = cal.date(from: dateComponents ) else {
    // The date you build up wasn't a valid day on the calendar
    return
}

//Now that your date is validated, get the day of the week

let weekdayIndex = cal.component(.weekday, from: date)

您会注意到“weekdayIndex”是一个整数。如果你想把它变成一个字符串,你可以这样做:

if let weekdayName = DateFormatter().weekdaySymbols?[ weekdayIndex - 1] {
    print("The weekday for your date is :: \(weekdayName)")
}

您当然可以使用let date = Date() 来获取当前星期几,而不是构建自己的日期

【讨论】:

  • 对不起,但这只会在编译时引发警告并在运行时使应用程序崩溃,甚至在 : 之后删除空格
  • 对不起,我试图记住这一点并搞砸了我的答案。现在修好了,我只是把它放到一个项目中验证了。
  • 我想知道的一件事:这是否取决于用户对日历应用程序的“周开始时间”设置?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 2018-07-15
相关资源
最近更新 更多