iPhone-如何检查日期是否为星期一? [英] iPhone - how may I check if a date is Monday?
问题描述
我正在尝试查找日期是否为星期一。
I'm trying to find if a date is Monday.
为此,我将按照以下方式进行操作:
To do this I proceed this way :
#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),
But this doesn't work... a and b does not contain anything useful (a equals 2147483647),
我还想知道 [calendar components:NSWeekdayCalendarUnit fromDate:retDate]
的用途是什么?在那种情况下……
I also wonder what can be the use of [calendar components:NSWeekdayCalendarUnit fromDate:retDate]
that is not useful anymore in that case...
我还发现这可以确认这一过程:
如何检查星期几(即星期二) ,星期五?)并比较两个NSDate?
I also found this that confirms the process : How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?
我错过了什么?
推荐答案
在这里,该方法可以通过整数返回日期:7 =星期六,1 =太阳,2 =星期一...
Here ya go, this works and returns days via ints: 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()$ c $来代替建立自己的日期c>而是获取星期几是什么
Instead of building your own date, you are of course allowed to use let date = Date()
instead to get what the current day of the week is
这篇关于iPhone-如何检查日期是否为星期一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!