我有一系列带有时间戳的日记帐分录。
class JournalNoteEntry {
var timeCreated: NSDate?
var value: Int?
var note: String?
}
如何针对今天,昨天,本周,本月等的条目筛选此数组,并绘制我的value
与timeCreated
并标记X轴
我已经搜索了很多基本需求但无法找到答案。
有人可以帮忙......
答案 0 :(得分:0)
let predicate = NSPredicate(format: "timeCreated == %f", NSDate().timeIntervalSince1970)
let arrFiltedArray = array .filteredArrayUsingPredicate(predicate)
其中timeCreated包含timeIntervalSince1970作为您的日期,Means将您的数据类型从NSDate转换为double
答案 1 :(得分:0)
由于你是在Swift 3中编写的,你应该使用原生的Swift类型而不是Foundation的类(那些以NS...
开头的类):
class JournalNoteEntry {
var timeCreated: Date?
var value: Int?
var note: String?
}
关于你的问题:让我们编写一个简单的函数来过滤开始日期和结束日期之间的所有条目:
func entries(in journal: [JournalNoteEntry], from: Date, to: Date) -> [JournalNoteEntry] {
return journal.filter {
guard let timeCreated = $0.timeCreated else {
return false
}
// Notice that this is half-open range
return from <= timeCreated && timeCreated < to
}
}
您的大部分努力将是确定日期范围。一种方法是通过Calendar
类的扩展名:
extension Calendar {
func todayRange() -> (Date, Date) {
let startDate = self.startOfDay(for: Date())
let endDate = self.date(byAdding: .day, value: 1, to: startDate)!
return (startDate, endDate)
}
func yesterdayRange() -> (Date, Date) {
let endDate = self.startOfDay(for: Date())
let startDate = self.date(byAdding: .day, value: -1, to: endDate)!
return (startDate, endDate)
}
func thisWeekRange() -> (Date, Date) {
var components = DateComponents()
components.weekday = self.firstWeekday
let startDate = self.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime, direction: .backward)!
let endDate = self.nextDate(after: startDate, matching: components, matchingPolicy: .nextTime)!
return (startDate, endDate)
}
func thisMonthRange() -> (Date, Date) {
var components = self.dateComponents([.era, .year, .month], from: Date())
components.day = 1
let startDate = self.date(from: components)!
let endDate = self.date(byAdding: .month, value: 1, to: startDate)!
return (startDate, endDate)
}
}
// Run this in Playground to see it formatted in your local timezone
// If you call print(), it will always display in UTC
// Assuming today = Nov 7, 2016
Calendar.current.todayRange() // "Nov 7, 2016, 12:00 AM", "Nov 8, 2016, 12:00 AM"
Calendar.current.yesterdayRange() // "Nov 6, 2016, 12:00 AM", "Nov 7, 2016, 12:00 AM"
Calendar.current.thisWeekRange() // "Nov 6, 2016, 12:00 AM", "Nov 13, 2016, 12:00 AM"
Calendar.current.thisMonthRange() // "Nov 1, 2016, 12:00 AM", "Dec 1, 2016, 12:00 AM"
获取当月内的所有日记帐分录:
// journal is an array of JournalNoteEntry
let (startDate, endDate) = Calendar.current.thisMonthRange()
let results = entries(in: journal, from: startDate, to: endDate)