如何获得本月的前7天如果今天是18岁我知道如何获得,但如果今天是11月3日怎么办?如何在Int?
中获取上个月(10月)的最后4天答案 0 :(得分:25)
使用NSCalendar
和NSDateComponents
:
let cal = NSCalendar.currentCalendar()
// start with today
var date = cal.startOfDayForDate(NSDate())
var days = [Int]()
for i in 1 ... 7 {
// get day component:
let day = cal.component(.DayCalendarUnit, fromDate: date)
days.append(day)
// move back in time by one day:
date = cal.dateByAddingUnit(.DayCalendarUnit, value: -1, toDate: date, options: nil)!
}
println(days)
Swift 2.2更新(Xcode 7.3.1):
let cal = NSCalendar.currentCalendar()
var date = cal.startOfDayForDate(NSDate())
var days = [Int]()
for i in 1 ... 7 {
let day = cal.component(.Day, fromDate: date)
days.append(day)
date = cal.dateByAddingUnit(.Day, value: -1, toDate: date, options: [])!
}
print(days)
更新 Swift 3(Xcode 8 beta 2):
let cal = Calendar.current
var date = cal.startOfDay(for: Date())
var days = [Int]()
for i in 1 ... 7 {
let day = cal.component(.day, from: date)
days.append(day)
date = cal.date(byAdding: .day, value: -1, to: date)!
}
print(days)
答案 1 :(得分:6)
与@MartinR相同的策略回答,尽可能短:
let cal = NSCalendar.currentCalendar()
let date = NSDate()
var result = map(-6...0) { delta -> Int in
cal.component(.DayCalendarUnit, fromDate: cal.dateByAddingUnit(.DayCalendarUnit, value: delta, toDate: date, options: nil)!)
}
答案 2 :(得分:4)
您可以使用日历创建扩展程序,以帮助您进行日历计算:
Swift 3或更高版本
extension Date {
var day: Int {
return Calendar.current.component(.day, from: self)
}
func adding(days: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: days, to: self)!
}
var last7days: [Int] {
return (1...7).map {
adding(days: -$0).day
}
}
func near(days: Int) -> [Int] {
return days == 0 ? [day] : (1...abs(days)).map {
adding(days: $0 * (days < 0 ? -1 : 1) ).day
}
}
}
用法:
let last7Days = Date().last7days // [29, 28, 27, 26, 25, 24, 23]
let last7Days2 = Date().near(days: -7) // [29, 28, 27, 26, 25, 24, 23]
let next7Days = Date().near(days: 7) // [27, 28, 29, 30, 31, 1, 2]
与@rintaro回答相同的策略,尽可能短;)(添加对负值的支持,并将其作为日期扩展,以便能够使用任何日期作为输入)
extension Date {
func closest(days: Int) -> [Int] {
return days == 0 ? [] : (1...abs(days)).map { delta -> Int in Calendar.current.component(.day, from: Calendar.current.date(byAdding: .day, value: delta * (days >= 0 ? 1 : -1), to: self)!) }
}
}
用法:
let next7Days2 = Date().closest(days: 7) // [27, 28, 29, 30, 31, 1, 2]
let last7Days3 = Date().closest(days: -7) // [25, 24, 23, 22, 21, 20, 19]
let next2Days = Date().closest(days: 2) // [27, 28]
let last2Days = Date().closest(days: -2) // [25, 24]
答案 3 :(得分:2)
受到this回答的启发,
获取以前 N 天的列表作为字符串数组。
extension Date {
static func getDates(forLastNDays nDays: Int) -> [String] {
let cal = NSCalendar.current
// start with today
var date = cal.startOfDay(for: Date())
var arrDates = [String]()
for _ in 1 ... nDays {
// move back in time by one day:
date = cal.date(byAdding: Calendar.Component.day, value: -1, to: date)!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from: date)
arrDates.append(dateString)
}
print(arrDates)
return arrDates
}
}
用法:
let last7Days = Date.getDates(forLastNDays: 7)
debugPrint(last7Days)
//Today(2017-11-19) it prints: ["2017-11-18", "2017-11-17", "2017-11-16", "2017-11-15", "2017-11-14", "2017-11-13", "2017-11-12"]
答案 4 :(得分:1)
它可能不是最快的代码。但你明白了这一点:)
import Foundation
let lastSevenDay: [Int] = {
var days = [Int]()
let secondsInADay: NSTimeInterval = 24 * 60 * 60
let now = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
for i in 1...7 {
let theDate = now.dateByAddingTimeInterval(-secondsInADay * NSTimeInterval(7 - i))
let dateComponent = calendar.components(NSCalendarUnit.CalendarUnitDay, fromDate: theDate)
let dayOfMonth = dateComponent.day
days.append(dayOfMonth)
}
return days
}()
答案 5 :(得分:1)
我修改了rintaro答案,以便在NSArray的NSArray中获取过去的日期,以获得所有值,包括过去的日期,月份和年份。您只需要像这样调用此代码段
println(getPastDates(2))
获取包含过去日期的完整列表
( { 天= 30; 月= 11; 年= 2014年; }, { 天= 29; 月= 11; 年= 2014年; } )
func getPastDates(days: Int) -> NSArray {
var dates = NSMutableArray()
let cal = NSCalendar.currentCalendar()
var today = cal.startOfDayForDate(NSDate())
for i in 1 ... days {
let day = cal.component(.DayCalendarUnit, fromDate: today)
let month = cal.component(.MonthCalendarUnit, fromDate: today)
let year = cal.component(.YearCalendarUnit, fromDate: today)
var date = NSMutableDictionary()
date.setValue(day, forKey: "day")
date.setValue(month, forKey: "month")
date.setValue(year, forKey: "year")
dates.addObject(date)
// move back in time by one day:
today = cal.dateByAddingUnit(.DayCalendarUnit, value: -1, toDate: today, options: nil)!
}
return dates
}
答案 6 :(得分:1)
我更新
Alejandro Luengo的代码。它适用于Swift4
source_file.hs:8:13:
No instance for (Show b)
Possible fix:
add (Show b) to the context of
the type signature for pair :: Int -> b -> (Int, b)
When checking that: forall a b. Show b => a -> b -> (a, b)
is more polymorphic than: forall b. Int -> b -> (Int, b)
When checking that instance signature for ‘pair’
is more general than its signature in the class
Instance sig: forall a b. Show b => a -> b -> (a, b)
Class sig: forall b. Int -> b -> (Int, b)
In the instance declaration for ‘Pair Int’
答案 7 :(得分:1)
Swift4
与@MartinR相同的策略,@rintaro回答,请尽可能短:
let calendar = Calendar.current
let date = Date()
let result: [Int] = (-6...0).map { delta -> Int in
calendar.component(.day, from: calendar.date(byAdding: .day, value: delta, to: date)!)
}
答案 8 :(得分:0)
您想使用NSCalendar
来获取最近7天。这是一个代码片段,用于演示11月3日的行动:
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
dateFormatter.locale = NSLocale(localeIdentifier: "en_GB")
let date = dateFormatter.dateFromString("03/11/14")!
println("date = \(dateFormatter.stringFromDate(date))")
let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var previous7days: Array<Int> = []
for i in 0...6 {
let prevDate = calendar.dateByAddingUnit(.CalendarUnitDay, value: -i, toDate: date, options: nil)
previous7days.insert(calendar.component(.CalendarUnitDay, fromDate: prevDate!), atIndex: 0)
}
println("last 7 days: \(previous7days)")