得到NSDate今天,昨天,本周,上周,本月,上个月…variables

我正在试图做的是今天,昨天,本周,本周,本月,上个月的variablesNSDate准备好比较的头添加在UITableView的titleForHeaderInSection

我想要的是在下面的代码2009-12-11中手动完成的

NSDate *today = [NSDate dateWithString:@"2009-12-11 00:00:00 +0000"]; NSDate *yesterday = [NSDate dateWithString:@"2009-12-10 00:00:00 +0000"]; NSDate *thisWeek = [NSDate dateWithString:@"2009-12-06 00:00:00 +0000"]; NSDate *lastWeek = [NSDate dateWithString:@"2009-11-30 00:00:00 +0000"]; NSDate *thisMonth = [NSDate dateWithString:@"2009-12-01 00:00:00 +0000"]; NSDate *lastMonth = [NSDate dateWithString:@"2009-11-01 00:00:00 +0000"]; 

根据date和时间编程指南进行修改 :

 // Right now, you can remove the seconds into the day if you want NSDate *today = [NSDate date]; // All intervals taken from Google NSDate *yesterday = [today dateByAddingTimeInterval: -86400.0]; NSDate *thisWeek = [today dateByAddingTimeInterval: -604800.0]; NSDate *lastWeek = [today dateByAddingTimeInterval: -1209600.0]; // To get the correct number of seconds in each month use NSCalendar NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83]; NSDate *lastMonth = [today dateByAddingTimeInterval: -5259487.66]; 

如果你想要正确的天数取决于你应该使用NSCalendar

可能是一个更好的方式来写这个,但在这里,我提出本的NSCalendarbuild议,并从那里工作到NSDateComponents

 NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]]; [components setHour:-[components hour]]; [components setMinute:-[components minute]]; [components setSecond:-[components second]]; NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight); [components setHour:-24]; [components setMinute:0]; [components setSecond:0]; NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0]; components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]]; [components setDay:([components day] - ([components weekday] - 1))]; NSDate *thisWeek = [cal dateFromComponents:components]; [components setDay:([components day] - 7)]; NSDate *lastWeek = [cal dateFromComponents:components]; [components setDay:([components day] - ([components day] -1))]; NSDate *thisMonth = [cal dateFromComponents:components]; [components setMonth:([components month] - 1)]; NSDate *lastMonth = [cal dateFromComponents:components]; NSLog(@"today=%@",today); NSLog(@"yesterday=%@",yesterday); NSLog(@"thisWeek=%@",thisWeek); NSLog(@"lastWeek=%@",lastWeek); NSLog(@"thisMonth=%@",thisMonth); NSLog(@"lastMonth=%@",lastMonth); 

NSDateComponents很高兴得到今天:

 NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *date = [NSDate date]; NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date]; NSDate *today = [cal dateFromComponents:comps]; 

这会创build一个只有年,月和日的NSDate:

 (gdb) po today 2010-06-22 00:00:00 +0200 

要得到昨天等你可以使用NSDateComponents计算它:

 NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:-1]; NSDate *yesterday = [cal dateByAddingComponents:components toDate:today options:0]; 
 + (NSDate*)dateFor:(enum DateType)dateType { NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]]; if(dateType == DateYesterday) { comps.day--; } else if(dateType == DateThisWeek) { comps.weekday = 1; } else if(dateType == DateLastWeek) { comps.weekday = 1; comps.week--; } else if(dateType == DateThisMonth) { comps.day = 1; } else if(dateType == DateLastMonth) { comps.day = 1; comps.month--; } else if(dateType != DateToday) return nil; return [calendar dateFromComponents:comps]; } 

Swift 2

 let today = NSDate() let yesterday = today.dateByAddingTimeInterval(-86400.0) let thisWeek = today.dateByAddingTimeInterval(-604800.0) let lastWeek = today.dateByAddingTimeInterval(-1209600.0) let thisMonth = today.dateByAddingTimeInterval(-2629743.83) let lastMonth = today.dateByAddingTimeInterval(-5259487.66) // components of the date let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) let components = calendar.components([.Year, .Month, .Day], fromDate: today) let (year, month, day) = (components.year, components.month, components.day) 

Swift 3

 let today = Date() let yesterday = today.addingTimeInterval(-86400.0) let thisWeek = today.addingTimeInterval(-604800.0) let lastWeek = today.addingTimeInterval(-1209600.0) let thisMonth = today.addingTimeInterval(-2629743.83) let lastMonth = today.addingTimeInterval(-5259487.66) // components of the date var calendar = Calendar(identifier: Calendar.Identifier.gregorian) let components = calendar.dateComponents([.year, .month, .day], from: today) let (year, month, day) = (components.year, components.month, components.day) 

Swift 3中 ,请注意date组件是可选的。

其他答案只是没有为我工作(也许是因为我的时区)。 这是我如何做到的:

 - (BOOL)isOnThisWeek:(NSDate *)dateToCompare { NSCalendar * calendar = [NSCalendar currentCalendar]; NSDate * today = [NSDate date]; int todaysWeek = [[calendar components: NSWeekCalendarUnit fromDate:today] week]; int dateToCompareWeek = [[calendar components: NSWeekCalendarUnit fromDate:dateToCompare] week]; int todaysYear = [[calendar components:NSYearCalendarUnit fromDate:today] year]; int dateToCompareYear = [[calendar components:NSYearCalendarUnit fromDate:dateToCompare] year]; if (todaysWeek == dateToCompareWeek && todaysYear == dateToCompareYear) { return YES; } return NO; } 

如果您使用的是iOS 10+或MacOS 10.12+,则可以使用这两种Calendar方法正确执行此操作。

  • func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date? ( docs )
  • func dateInterval(of component: Calendar.Component, for date: Date) -> DateInterval? ( docs )

下面是一个如何在Swift 3中使用这些方法的示例,以及我的时区中的游乐场输出。

 let calendar = Calendar.current let now = Date() // => "Apr 28, 2017, 3:33 PM" let yesterday = calendar.date(byAdding: .day, value: -1, to: now) // => "Apr 29, 2017, 3:33 PM" let yesterdayStartOfDay = calendar.startOfDay(for: yesterday!) // => ""Apr 29, 2017, 12:00 AM" let thisWeekInterval = calendar.dateInterval(of: .weekOfYear, for: now) // => 2017-04-23 04:00:00 +0000 to 2017-04-30 04:00:00 +0000 let thisMonthInterval = calendar.dateInterval(of: .month, for: now) // => 2017-04-01 04:00:00 +0000 to 2017-05-01 04:00:00 +0000 let aDateInLastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: now) let lastWeekInterval = calendar.dateInterval(of: .weekOfYear, for: aDateInLastWeek!) // => 2017-04-16 04:00:00 +0000 to 2017-04-23 04:00:00 +0000 let aDateInLastMonth = calendar.date(byAdding: .month, value: -1, to: now) let lastMonthInterval = calendar.dateInterval(of: .weekOfYear, for: aDateInLastMonth!) // => 2017-03-26 04:00:00 +0000 to 2017-04-02 04:00:00 +0000 

奖金:您可以使用DateInterval来testingdate是否在该范围内。 从上面继续:

 thisWeekInterval!.contains(now) // => true lastMonthInterval!.contains(now) // => false 
 NSDate *today = [NSDate date]; // Today's date NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents =[gregorian componentsNSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; NSInteger day = [weekdayComponents day]; 

我真的很喜欢这个项目中包含的THCalendarInfo对象:

http://github.com/jaredholdcroft/kcalendar

我不能完全find原文。 使用这个对象,你可以移动到前一天,一个星期的开始,一个月的开始,一个星期的某一天,一个月中的某一天……等等。

 NSDate *today = [[NSDate alloc] initWithTimeIntervalSinceNow:0]; 

这是为了检查date是否在这个月

 func isOnThisMonth(dateToCompare: NSDate) -> Bool { let calendar: NSCalendar = NSCalendar.currentCalendar() let today: NSDate = NSDate() let todaysWeek: Int = calendar.components(NSCalendarUnit.Month, fromDate: today).month let dateToCompareWeek: Int = calendar.components(.Month, fromDate: dateToCompare).month let todaysYear: Int = calendar.components(NSCalendarUnit.Year, fromDate: today).year let dateToCompareYear: Int = calendar.components(NSCalendarUnit.Year, fromDate: dateToCompare).year if todaysWeek == dateToCompareWeek && todaysYear == dateToCompareYear { return true } return false } 

而第二个只能像这样变弱的calendarUnittypes

 func isOnThisWeek(dateToCompare: NSDate) -> Bool { let calendar: NSCalendar = NSCalendar.currentCalendar() let today: NSDate = NSDate() let todaysWeek: Int = calendar.components(NSCalendarUnit.Weekday, fromDate: today).weekday let dateToCompareWeek: Int = calendar.components(.Weekday, fromDate: dateToCompare).weekday let todaysYear: Int = calendar.components(NSCalendarUnit.Year, fromDate: today).year let dateToCompareYear: Int = calendar.components(NSCalendarUnit.Year, fromDate: dateToCompare).year if todaysWeek == dateToCompareWeek && todaysYear == dateToCompareYear { return true } return false } 

我希望这有助于某人谢谢。

我已经回答了一个类似的问题,这就是为什么我的答案更好:

  • Swift 3
  • 利用DateFormatter的“昨天”和“今天”。 这已经被苹果公司翻译,这可以节省你的工作!
  • 使用DateComponentsFormatter已经翻译的“1周”string。 (对苹果来说,再次减less工作量)。你所要做的就是翻译“%@前”string。 🙂
  • 其他答案错误地计算了当天从“今天”切换到“昨天”等时间。固定常数是一个很大的NO-NO,因为原因 。 此外,其他答案使用当前date/时间来使用当前date/时间的结尾
  • 使用autoupdatingCurrent作为日历和语言环境,确保您的应用程序立即与Settings.app中用户的日历和语言首选项保持一致