我一直在研究,但我无法找到解决问题的确切方法。我一直试图从一个约会前1小时前得到。我怎样才能在swift中实现这一目标?
答案 0 :(得分:51)
对于涉及NSDate的正确计算,考虑到不同日历的所有边缘情况(例如,在节省时间之间切换),您应该使用NSCalendar类:
Swift 3 +
let earlyDate = Calendar.current.date(
byAdding: .hour,
value: -1,
to: Date())
<强>旧版强>
// Get the date that was 1hr before now
let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Hour,
value: -1,
toDate: NSDate(),
options: [])
答案 1 :(得分:32)
使用此方法并粘贴到助手类中。
Swift 3和XCode 8.3的更新
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
Log.d("push","msg type: " + messageType);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
} else if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.d("push notify msg: ", extras.toString());
sendNotification(extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
使用此方法:
class func timeAgoSinceDate(_ date:Date,currentDate:Date, numericDates:Bool) -> String {
let calendar = Calendar.current
let now = currentDate
let earliest = (now as NSDate).earlierDate(date)
let latest = (earliest == now) ? date : now
let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: earliest, to: latest, options: NSCalendar.Options())
if (components.year! >= 2) {
return "\(components.year!) years ago"
} else if (components.year! >= 1){
if (numericDates){
return "1 year ago"
} else {
return "Last year"
}
} else if (components.month! >= 2) {
return "\(components.month!) months ago"
} else if (components.month! >= 1){
if (numericDates){
return "1 month ago"
} else {
return "Last month"
}
} else if (components.weekOfYear! >= 2) {
return "\(components.weekOfYear!) weeks ago"
} else if (components.weekOfYear! >= 1){
if (numericDates){
return "1 week ago"
} else {
return "Last week"
}
} else if (components.day! >= 2) {
return "\(components.day!) days ago"
} else if (components.day! >= 1){
if (numericDates){
return "1 day ago"
} else {
return "Yesterday"
}
} else if (components.hour! >= 2) {
return "\(components.hour!) hours ago"
} else if (components.hour! >= 1){
if (numericDates){
return "1 hour ago"
} else {
return "An hour ago"
}
} else if (components.minute! >= 2) {
return "\(components.minute!) minutes ago"
} else if (components.minute! >= 1){
if (numericDates){
return "1 minute ago"
} else {
return "A minute ago"
}
} else if (components.second! >= 3) {
return "\(components.second!) seconds ago"
} else {
return "Just now"
}
}
答案 2 :(得分:10)
请阅读NSDate
课程参考。
let oneHourAgo = NSDate.dateWithTimeIntervalSinceNow(-3600)
应该这样做。
或者,对于任何NSDate
对象:
let oneHourBack = myDate.dateByAddingTimeInterval(-3600)
答案 3 :(得分:7)
根据您的需要,您可以从一个Date
实例中选择以下3个Swift 3方法中的一个来获取。{/ p>
date(byAdding:value:to:wrappingComponents:)
Calendar
有一个名为date(byAdding:value:to:wrappingComponents:)
的方法。 date(byAdding:value:to:wrappingComponents:)
有以下声明:
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
返回一个新的
Date
,表示通过将特定组件的数量添加到给定日期而计算的日期。
下面的Playground代码显示了如何使用它:
import Foundation
let now = Date()
let oneHourAgo = Calendar.current.date(byAdding: .hour, value: -1, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
date(byAdding:to:wrappingComponents:)
Calendar
有一个名为date(byAdding:to:wrappingComponents:)
的方法。 date(byAdding:value:to:wrappingComponents:)
有以下声明:
func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?
返回一个新的
Date
,表示通过将组件添加到给定日期而计算的日期。
下面的Playground代码显示了如何使用它:
import Foundation
let now = Date()
var components = DateComponents()
components.hour = -1
let oneHourAgo = Calendar.current.date(byAdding: components, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
替代:
import Foundation
// Get the date that was 1hr before now
let now = Date()
let components = DateComponents(hour: -1)
let oneHourAgo = Calendar.current.date(byAdding: components, to: now)
print(now) // 2016-12-19 21:52:04 +0000
print(String(describing: oneHourAgo)) // Optional(2016-12-19 20:52:04 +0000)
addingTimeInterval(_:)
(谨慎使用) Date
有一个名为addingTimeInterval(_:)
的方法。 addingTimeInterval(_:)
有以下声明:
func addingTimeInterval(_ timeInterval: TimeInterval) -> Date
通过向此
Date
添加TimeInterval
来返回新的Date
。
请注意,此方法附带警告:
这仅调整绝对值。如果您希望添加小时,天,月等日历概念,则必须使用
Calendar
。这将考虑到诸如夏令时,具有不同天数的月份等复杂性。
下面的Playground代码显示了如何使用它:
import Foundation
let now = Date()
let oneHourAgo = now.addingTimeInterval(-3600)
print(now) // 2016-12-19 21:52:04 +0000
print(oneHourAgo) // 2016-12-19 20:52:04 +0000
答案 4 :(得分:5)
如果您使用的是NSDate
,则可以执行以下操作:
let date = NSDate()
date.dateByAddingTimeInterval(-3600)
它会将date
对象更改为“1小时前”。
答案 5 :(得分:4)
Swift3:
-----server 1 table :
MaintenanceID SerialID MDToolID MaintDate ComponentID Notes
218 8 4 2016-05-26 01:00:00.0000000 NULL pivot
219 9 4 2016-08-06 21:15:00.0000000 NULL
220 130 4 2016-08-09 00:00:00.0000000 NULL NULL
-----server 2 table :
MaintenanceID SerialID MDToolID MaintDate ComponentID Notes
45 130 4 2016-02-09 00:00:00.0000000 NULL CHECK ME
49 131 5 2016-02-09 00:00:00.0000000 NULL CHECK ME
答案 6 :(得分:2)
通过创建Date的扩展,我实现了很久以前的功能。以下是:
extension Date {
// Returns the number of years
func yearsCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
}
// Returns the number of months
func monthsCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
// Returns the number of weeks
func weeksCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
// Returns the number of days
func daysCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
// Returns the number of hours
func hoursCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
// Returns the number of minutes
func minutesCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
// Returns the number of seconds
func secondsCount(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
// Returns time ago by checking if the time differences between two dates are in year or months or weeks or days or hours or minutes or seconds
func timeAgo(from date: Date) -> String {
if yearsCount(from: date) > 0 { return "\(yearsCount(from: date))years ago" }
if monthsCount(from: date) > 0 { return "\(monthsCount(from: date))months ago" }
if weeksCount(from: date) > 0 { return "\(weeksCount(from: date))weeks ago" }
if daysCount(from: date) > 0 { return "\(daysCount(from: date))days ago" }
if hoursCount(from: date) > 0 { return "\(hoursCount(from: date))hours ago" }
if minutesCount(from: date) > 0 { return "\(minutesCount(from: date))minutes ago" }
if secondsCount(from: date) > 0 { return "\(secondsCount(from: date))seconds ago" }
return ""
}
}
然后我通过计算当前日期和指定日期之间的差异得到时间:
let timeAgo = Date().timeAgo(from: sender.date)
答案 7 :(得分:1)
对于Swift 2:
extension NSDate {
func after(value: Int, calendarUnit:NSCalendarUnit) -> NSDate {
return calendar.dateByAddingUnit(calendarUnit, value: value, toDate: self, options: [])!
}
}
使用方法:
let lastHour = NSDate().after(-1, calendarUnit: .Hour)
答案 8 :(得分:1)
这适用于iOS 13 / Swift5。功劳归于Sourabh Sharma
func timeAgoSinceNow(numericDates: Bool = true) -> String {
let calendar = Calendar.current
let now = Date()
let earliest = (now as NSDate).earlierDate(self)
let latest = (earliest == now) ? self : now
let components: DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute,
NSCalendar.Unit.hour,
NSCalendar.Unit.day,
NSCalendar.Unit.weekOfYear,
NSCalendar.Unit.month,
NSCalendar.Unit.year,
NSCalendar.Unit.second],
from: earliest,
to: latest,
options: NSCalendar.Options())
guard
let year = components.year,
let month = components.month,
let weekOfYear = components.weekOfYear,
let day = components.day,
let hour = components.hour,
let minute = components.minute,
let second = components.second
else { return "A while ago"}
if year >= 1 {
return year >= 2 ? "\(year) years ago" : numericDates ? "1 year ago" : "Last year"
} else if month >= 1 {
return month >= 2 ? "\(month) months ago" : numericDates ? "1 month ago" : "Last month"
} else if weekOfYear >= 1 {
return weekOfYear >= 2 ? "\(weekOfYear) weeks ago" : numericDates ? "1 week ago" : "Last week"
} else if day >= 1 {
return day >= 2 ? "\(day) days ago" : numericDates ? "1 day ago" : "Yesterday"
} else if hour >= 1 {
return hour >= 2 ? "\(hour) hours ago" : numericDates ? "1 hour ago" : "An hour ago"
} else if minute >= 1 {
return minute >= 2 ? "\(minute) minutes ago" : numericDates ? "1 minute ago" : "A minute ago"
} else {
return second >= 3 ? "\(second) seconds ago" : "Just now"
}
}
用法:
var date = Date() // Or any date you wish to convert to text
print("\(date.timeAgoSinceNow())") // "Just Now"
答案 9 :(得分:0)
您还可以使用运算符
let date = Date()
let anHourAgo = date - TimeInterval(3600.0)
Apple Docs: https://developer.apple.com/documentation/foundation/date/2293436
答案 10 :(得分:0)
迅速5可以使用
let earlyDate = Calendar.current.date( byAdding: .hour, value: -1, to: Date())
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = df.string(from: earlyDate!)
输出将像波纹管一样
Current DateTime--> 2019-12-20 09:40:08
One Hour Previous Date Time--> 2019-12-20 08:40:08
答案 11 :(得分:0)
import Foundation
extension Date {
typealias Component = (value: Int, type: Calendar.Component)
init?(bySubtracting components: Component..., calendar: Calendar = Calendar.current, from date: Date) {
guard let date = date.subtract(components, calendar: calendar) else { return nil }
self = date
}
func subtract(_ components: Component..., calendar: Calendar = Calendar.current) -> Date? {
subtract(components, calendar: calendar)
}
func subtract(_ components: [Component], calendar: Calendar = Calendar.current) -> Date? {
components.reduce(self) { (result, component) -> Date? in
guard let date = result else { return nil }
return calendar.date(byAdding: component.type, value: (-1)*component.value, to: date)
}
}
static func beforeNow(difference component: Component..., calendar: Calendar = Calendar.current) -> Date? {
Date().subtract(component, calendar: calendar)
}
static func beforeNow(difference component: [Component], calendar: Calendar = Calendar.current) -> Date? {
Date().subtract(component, calendar: calendar)
}
}
extension Date {
static func - (date: Date, component: Date.Component) -> Date? { date.subtract(component, calendar: Calendar.current) }
static func -= (date: inout Date, component: Date.Component) {
guard let newDate = date.subtract(component, calendar: Calendar.current) else { return }
date = newDate
}
}
var currentDate = Date()
let date1 = Date(bySubtracting: (30, .day), from: currentDate)
let date2 = Date().subtract((30, .day))
let date3 = Date().subtract([(1, .minute), (2, .hour), (3, .day), (4, .month)])
let component = Date.Component(value: 1, type: .day)
let date4 = Date.beforeNow(difference: component)
let date5 = Date.beforeNow(difference: (1, .minute), (2, .hour), (3, .day), (4, .month))
let date6 = Date.beforeNow(difference: [(1, .minute), (2, .hour), (3, .day), (4, .month)])
let date7 = currentDate - (1, .day)
currentDate -= Date.Component(value: 1, type: .day)
答案 12 :(得分:0)
let now = Date()
let nowMinusTwoAndAHalfHours = now - 2.5*60*60
print(now)
print(nowMinusTwoAndAHalfHours)
答案 13 :(得分:0)
Calendar.current.date( byAdding: .hour, value: -1, to: Date())