Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

iphone - How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

I'm looking two do two things:

  1. Check if a week has gone by (based on the day of the week)
  2. Check if a day has gone by (based on the date)

I'm not sure what the best way to solve this is, since when comparing two NSDates (one at 1/1/09 at 21:30 and another at 1/2/09 at 00:30) I can't just see if 24 hours has gone by since in this case it hasn't. I can solve this by just getting the date 1/1/09 from the NSDate, but I'm unsure how to do this based on the documentation and google links that I saw.

For the other issue, I don't know how to know what day of the week it is given a date. I'd like to if 1/1/09 is a Tuesday, Monday, etc... Is there any library that let's you calculate this? This obviously needs to take into account leap years and a tons of other stuff... Maybe there's an objective-c library for this?

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use components:fromData: message of the NSCalendar class to get the individual date components:

// Sunday = 1, Saturday = 7
int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:theDate] weekday];

To compare two dates, just use the compare: message:

switch([date1 compare:date2])
{
case NSOrderedSame:       /* they are the same date */ break;
case NSOrderedAscending:  /* date1 precedes date2 */ break;
case NSOrderedDescending: /* date2 precedes date1 */ break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...