我正在努力弄清楚如何在上午12:00的最前一个星期日动态创建日期对象
我以为我可以得到今天的日期,然后减去当周的当天+ 1,此时我可以减去当天的时间到达上午12点.
到目前为止,我有一周的当天:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
Run Code Online (Sandbox Code Playgroud)
在这一点上,我可以得到今天的日期并减去weekday一天中*秒的差异.但是,我怎样才能在几秒钟内获得今天的时间?
无需手动计算秒数(由于夏令时等因此无论如何都是危险的).以下应该完全符合您的要求:
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering
NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
[nowComponents setWeekday:1]; //Sunday
[nowComponents setHour:0]; // 12:00 AM = midnight (12:00 PM would be 12)
[nowComponents setMinute:0];
[nowComponents setSecond:0];
NSDate *previousSunday = [calendar dateFromComponents:nowComponents];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2257 次 |
| 最近记录: |