2
A
回答
6
對於time/date calculations使用NSDateComponents。
清單2拿週日在本週
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
/*
Optional step:
beginningOfWeek now has the same hour, minute, and second as the original date (today).
To normalize to midnight, extract the year, month, and day components and create a new date from those components.
*/
NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents:components];
2014年3月
其實還有一個更聰明的方式
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setFirstWeekday:2]; //2 is monday. 1:Sunday .. 7:Saturday don't set it, if user's locale should determine the start of a week
NSDate *now = [NSDate date];
NSDate *monday;
[cal rangeOfUnit:NSWeekCalendarUnit // we want to have the start of the week
startDate:&monday // we will write the date object to monday
interval:NULL // we don't care for the seconds a week has
forDate:now]; // we want the monday of today's week
如果你確實改變平日代表本週的開始(週日vs 。星期一),你應該在這段代碼後改回它。
相關問題
- 1. 如何獲得特定一週中特定日期的日期
- 2. 如何獲得SAS中的前一個星期一(前一週的星期一)?
- 3. 獲得周第一天(星期日)
- 4. 如何獲得星期一開始的特定日期的星期幾?
- 5. PHP如何獲得給定日期下週的星期一和星期日的日期?
- 6. 如果週六或週日落在星期一或星期日
- 7. 本週星期一日期
- 8. 如何獲得一天的日期在一個星期在C#
- 9. 如何使用星期編號獲取一週的星期一日期
- 10. Excel - 如何獲取日期是一週中的特定日期?
- 11. 如何獲得從下一個星期日結束的周
- 12. 在.net中,知道週數如何獲得星期幾日期?
- 13. 在SQL中獲取本週的星期一的完整日期?
- 14. 獲取本週的開始日期和結束日期(星期一從星期一開始,星期日結束)
- 15. pl sql如何獲得一週的日期爲oracle db日期
- 16. 我如何在Matlab中獲得特定日期的一週中的某一天
- 17. 獲取本週的星期一是週一至週日(VBScript)
- 18. 從星期一到星期日獲取當週工作日
- 19. Java - 獲取星期一的一週的日期在那一週給出一個日期
- 20. 在Postgres獲取本週的星期一的日期?
- 21. 獲取本週第一個星期一的日期?
- 22. Android顯示從一週到另一週的日期(星期四至星期四)
- 23. Django的日期字段得到一個星期就像星期日星期一
- 24. 如何使用jquery得到上週的星期日日期
- 25. osx星期一日期本週bash
- 26. Sql獲得員工每週工作時間每週的開始日期(例如星期,星期一,星期二等的開始日期)
- 27. php在一個月內獲得所有星期日的日期
- 28. PHP取得ISO開始日期不是星期一的日期的ISO週數
- 29. 得到特殊日期的
- 30. 獲取昨天的日期,如果星期一得到週末範圍
看起來很複雜:>。但它是一個非常好的例子。謝謝 – adamseve 2010-10-08 14:01:58