简体   繁体   English

如何从本周的工作日名称中获取特定日期

[英]How to get specific date from weekday name in this week

How can we get date of a specific day in current week with day name (Between monday and sunday)? 如何获得带有日期名称的当前周中特定日期的日期(星期一至星期日之间)? eg I want to learn what is the date of this sunday or what was the date of last monday. 例如,我想了解这个星期几或上个星期一的日期。

EDIT: Here how I solved the problem with the help of @juniperi 's link 编辑:在这里我如何解决@juniperi的链接的问题

//To get current day
CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef tz = CFTimeZoneCopySystem();
SInt32 currentWeekdayNumber = CFAbsoluteTimeGetDayOfWeek(at, tz);

//We are adding or substracting from the day we want and add to the current date
NSDate *now = [NSDate date];
int daysToAdd = theDayNumberWeWant - currentWeekdayNumber;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
int yourDOW = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit
    fromDate:yourDate] weekday];

This the way you can get which day is there for current date, for eg: Monday, Tuesday, etc. 这样,您可以获取当前日期的哪一天,例如:星期一,星期二等。

According to that, you can calculate next/prev day and/or dates, both: 据此,您可以计算下一个/上一个日期和/或日期,两者都可以:

For example: 例如:

(Sunday is represented with 1.) 20 Jun 2014 is Friday then result is 6. Then it means last Monday is: date - (currentDay - requiredDay) = 20 - ( 6 (friday) - 2 (monday)) = 20 - (4) = 16 (星期日用1表示。)2014年6月20日是星期五,结果是6。则表示上周一是:日期-(currentDay-requiredDay)= 20-(6(星期五)-2(星期一))= 20-( 4)= 16

It means, 16 Jun 2014 is the last Monday. 也就是说,2014年6月16日是最后一个星期一。

Hope this helps. 希望这可以帮助。 For more details, refer NSDateComponents. 有关更多详细信息,请参见NSDateComponents。

Pass your date this method will return you date of first day in the week this date exists. 传递您的日期,此方法将返回您存在该日期的第一天的日期。 like if you pass current date you will get date of first day in current week. 就像您传递当前日期一样,您将获得当前星期第一天的日期。 Like this you can calculate date of other days. 这样,您可以计算其他日期的日期。

+ (NSDate *) getFirstDayOfTheWeekFromDate:(NSDate*)givenDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
[components setWeekday:1];
[components setWeek:[components week]];

return [calendar dateFromComponents:components];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM