在上午12:00动态创建上一个星期日的日期 [英] dynamically create date for previous sunday at 12:00 AM

查看:68
本文介绍了在上午12:00动态创建上一个星期日的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清楚如何在上午12:00的最前一个星期日动态创建一个日期对象

I'm struggling to figure out how to dynamically create a date object for the most previous sunday at 12:00 AM

我以为我今天可以得到日期然后减去当周的当天+ 1,此时我可以减去当天的时间到达上午12点。

I was thinking I could get today's date and then subtract the current day of the week + 1 at which point I could just subtract the time of the day do get down to 12AM.

到目前为止,我有当前的星期几:

so far I have the current day of the week:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];

此时我可以获得今天的日期并减去工作日的差异一天中的*秒。但是,我怎样才能在几秒钟内获得今天的时间?

at which point I can get today's date and subtract the difference of weekday * seconds in a day. However, how can I get today's time in seconds ??

推荐答案

无需手动计算秒数(这无论如何都是危险的夏令时等)。以下内容应该完全符合您的要求:

No need to manually calculate seconds (which is dangerous anyway because of daylight saving etc.). The following should do exactly what you want:

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];

这篇关于在上午12:00动态创建上一个星期日的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆