如何计算本周的第一个 NSDate?

发布于 2024-09-15 05:03:44 字数 189 浏览 10 评论 0原文

即:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];

例如,今天是 8 月 19 日,我想从上面的代码行获取 2010-08-15 12:00amNSDate 。谢谢!

i.e.:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];

for example, today is Aug 19, I'd want to get a NSDate of 2010-08-15 12:00am from above line of code. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

时光病人 2024-09-22 05:03:44

我认为该线程响应您正在寻找的内容: http: //www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826

但请注意,它不会将星期一处理为一周的第一天,因此您可能需要稍微调整一下通过减去 [gregorian firstWeekday] 而不是仅仅减去 1。另外,我将其修改为使用 -currentCalendar,但这取决于您:-)

NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// 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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
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];

I think this threads responds to what you're looking for: http://www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826

Note however that it doesn't handle Mondays as first days of the week, so you may have to tweek it a little by substracting [gregorian firstWeekday] instead of just 1. Also, I modified it to use -currentCalendar, but it's up to you :-)

NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// 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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
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];
倚栏听风 2024-09-22 05:03:44

为什么这么复杂? :)

func firstDateOfWeekWithDate(date: NSDate) -> NSDate {

    var beginningOfWeek: NSDate?

    calendar.rangeOfUnit(.WeekOfYear, startDate: &beginningOfWeek, interval: nil, forDate: date)

    return beginningOfWeek!

}

Why so complicated? :)

func firstDateOfWeekWithDate(date: NSDate) -> NSDate {

    var beginningOfWeek: NSDate?

    calendar.rangeOfUnit(.WeekOfYear, startDate: &beginningOfWeek, interval: nil, forDate: date)

    return beginningOfWeek!

}
衣神在巴黎 2024-09-22 05:03:44

如果第一个工作日设置为星期一 (2) 并且您要检查的日期是星期日,则 naixn 的解决方案将产生错误的结果。在这种情况下,您将在下周一得到结果。

正确的方法是按如下方式计算减法部分:

[componentsToSubtract setDay: - ((([weekdayComponents weekday] - [gregorian firstWeekday])
                                  + 7 ) % 7)];

假设您一周总是有 7 天。

The solution by naixn will produce wrong results if monday (2) is set of the firstWeekday and the date you are inspecting is sunday. In this case you will get as a result the monday of next week.

The correct way would be to calculate the subtraction components as follows:

[componentsToSubtract setDay: - ((([weekdayComponents weekday] - [gregorian firstWeekday])
                                  + 7 ) % 7)];

Assuming that you always have 7 days in a week.

杯别 2024-09-22 05:03:44
- (NSDate *)firstDateOfWeekWithDate:(NSDate *)date {

    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
    [components setDay:-((([weekdayComponents weekday] - [calendar firstWeekday]) + 5 ) % 7)];

    return [calendar dateFromComponents:components];
}
- (NSDate *)firstDateOfWeekWithDate:(NSDate *)date {

    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
    [components setDay:-((([weekdayComponents weekday] - [calendar firstWeekday]) + 5 ) % 7)];

    return [calendar dateFromComponents:components];
}
若无相欠,怎会相见 2024-09-22 05:03:44

这已经得到了回答,但正如 Wolfgang 指出的,接受的答案中有一个错误。如果第一个工作日设置为比相关 NSDate 更大的日期,则结果将不正确。这是一个完整的解决方案,适用于所有可能的 firstWeekday 值(示例使用星期一)。

- (NSDate *)weekOfDate:(NSDate *)originalDate
{
    NSCalendar *currentCal = [NSCalendar currentCalendar];
    [currentCal setFirstWeekday:2]; // Sun = 1, Mon = 2, etc.

    NSDateComponents *weekdayComponents = [currentCal components:NSCalendarUnitWeekday fromDate:originalDate];

    // Calculate the number of days to subtract and create NSDateComponents with them.
    NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
    NSInteger daysToSubtract = (([weekdayComponents weekday] - [currentCal firstWeekday]) + 7) % 7;
    [componentsToSubtract setDay:-1 * daysToSubtract];

    return [currentCal dateByAddingComponents:componentsToSubtract toDate:originalDate options:0];
}

This has already been answered, but as Wolfgang has pointed out, there is a bug in the accepted answer. If the first weekday is set as a greater date than the NSDate in question, the result will be incorrect. Here is a complete solution that works for all possible firstWeekday values (the example uses Monday).

- (NSDate *)weekOfDate:(NSDate *)originalDate
{
    NSCalendar *currentCal = [NSCalendar currentCalendar];
    [currentCal setFirstWeekday:2]; // Sun = 1, Mon = 2, etc.

    NSDateComponents *weekdayComponents = [currentCal components:NSCalendarUnitWeekday fromDate:originalDate];

    // Calculate the number of days to subtract and create NSDateComponents with them.
    NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
    NSInteger daysToSubtract = (([weekdayComponents weekday] - [currentCal firstWeekday]) + 7) % 7;
    [componentsToSubtract setDay:-1 * daysToSubtract];

    return [currentCal dateByAddingComponents:componentsToSubtract toDate:originalDate options:0];
}
未央 2024-09-22 05:03:44

最简单的解决方案:

func firstDayOfWeek(date: NSDate) -> NSDate {
  let calendar = NSCalendar.currentCalendar()
  var dateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitWeekOfMonth, fromDate: date)
  dateComponents.weekday = 1
  return calendar.dateFromComponents(dateComponents)!
}

The simplest solution:

func firstDayOfWeek(date: NSDate) -> NSDate {
  let calendar = NSCalendar.currentCalendar()
  var dateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitWeekOfMonth, fromDate: date)
  dateComponents.weekday = 1
  return calendar.dateFromComponents(dateComponents)!
}
度的依靠╰つ 2024-09-22 05:03:44

对于斯威夫特 4.1:

extension Date {
  var startOfWeek: Date? {
        let calendar = Calendar(identifier: .gregorian)
        return calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
    }
}

For Swift 4.1:

extension Date {
  var startOfWeek: Date? {
        let calendar = Calendar(identifier: .gregorian)
        return calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
    }
}
盛夏已如深秋| 2024-09-22 05:03:44

使用 NSDateComponent并将工作日设置为1。

Use NSDateComponents and set the weekday to 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文