iPhone SDK,如何获得NSDate对象的即将到来的星期五的20:00? [英] iPhone SDK, how to get NSDate object of coming friday's 20:00?

查看:90
本文介绍了iPhone SDK,如何获得NSDate对象的即将到来的星期五的20:00?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何得到即将到来的星期五的20点的NSDate?

Does anyone know how to get the NSDate of the coming friday's 20:00 ?

推荐答案

是,本文教您如何取得当周的星期日。

Yes, this article teaches you how to get the current week's Sunday.

我很快适应了星期五at 20:00(假设一个公历)

I quickly adapted it to get friday at 20:00 (Assuming a Gregorian calendar)

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 add to the current date.
The weekday value for Friday in the Gregorian calendar is 6, so add the difference between 6 and today to get the number of days to add.
Actually, on Saturday that will give you -1, so you want to subtract from 13 then take modulo 7
*/
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToAdd setDay: (13 - [weekdayComponents weekday]) % 7];

NSDate *friday = [gregorian dateByAddingComponents:componentsToAdd toDate:today options:0];

/*
friday 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: friday];

// And to set the time to 20:00
[components setHour:22];

friday = [gregorian dateFromComponents:components];

这篇关于iPhone SDK,如何获得NSDate对象的即将到来的星期五的20:00?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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