如何从iOS swift中的约会中获取1小时前的信息?
我一直在研究,但找不到解决问题的确切方法。我一直在试着在一个小时前从约会中恢复过来。如何在swift中实现这一点?请阅读如何从iOS swift中的约会中获取1小时前的信息?,ios,iphone,swift,date,Ios,Iphone,Swift,Date,我一直在研究,但找不到解决问题的确切方法。我一直在试着在一个小时前从约会中恢复过来。如何在swift中实现这一点?请阅读NSDate课程参考 let oneHourAgo = NSDate.dateWithTimeIntervalSinceNow(-3600) 我应该这样做 或者,对于任何NSDate对象: let oneHourBack = myDate.dateByAddingTimeInterval(-3600) Swift 4: let oneHourAgo = NSDate(tim
NSDate
课程参考
let oneHourAgo = NSDate.dateWithTimeIntervalSinceNow(-3600)
我应该这样做
或者,对于任何NSDate
对象:
let oneHourBack = myDate.dateByAddingTimeInterval(-3600)
Swift 4:
let oneHourAgo = NSDate(timeIntervalSinceNow: -3600)
var timeAgo:String=AppHelper.timeAgoSinceDate(date, numericDates: true)
Print("\(timeAgo)") // Ex- 1 hour ago
要正确计算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: [])
如果您使用的是
NSDate
,您可以执行以下操作:
let date = NSDate()
date.dateByAddingTimeInterval(-3600)
它会将
日期
对象更改为“1小时前”。使用此方法并粘贴到助手类中
为Swift 3和Xcode 8.3更新
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"
}
}
此方法的使用:
let oneHourAgo = NSDate(timeIntervalSinceNow: -3600)
var timeAgo:String=AppHelper.timeAgoSinceDate(date, numericDates: true)
Print("\(timeAgo)") // Ex- 1 hour ago
对于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)
根据您的需要,您可以从以下3种Swift 5方法中选择一种,从
Date
实例中提前一小时获取
1. <代码>日期(通过将:值:添加到:包装组件:)
Calendar
有一个名为的方法<代码>日期(通过添加:value:to:wrappingComponents:)具有以下声明:
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?
func addingTimeInterval(_ timeInterval: TimeInterval) -> Date
返回一个新的日期
,该日期表示通过向给定日期添加特定组件的数量来计算的日期
下面的操场代码显示了如何使用它:
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)
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
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
2. <代码>日期(通过将:添加到:包装组件:)
Calendar
有一个名为的方法<代码>日期(通过添加:value:to:wrappingComponents:)具有以下声明:
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?
func addingTimeInterval(_ timeInterval: TimeInterval) -> Date
返回新的日期
,表示通过向给定日期添加组件计算的日期
下面的操场代码显示了如何使用它:
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)
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
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
备选方案:
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)
3. <代码>添加时间间隔(:)(小心使用)
Date
有一个名为的方法addingTimeInterval(:)
具有以下声明:
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?
func addingTimeInterval(_ timeInterval: TimeInterval) -> Date
通过在此日期
中添加时间间隔
,返回新的日期
请注意,此方法附带警告:
这只会调整绝对值。如果您希望添加日历概念,如小时、天、月,则必须使用日历
。这将考虑到诸如夏令时、不同天数的月份等复杂性
下面的操场代码显示了如何使用它:
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)
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
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
迅捷3:
let now = Date()
let tempCalendar = Calendar.current
let alteredDate = tempCalendar.date(byAdding: .hour, value: -1, to: now)
我通过创建日期扩展来实现“时间前”功能。具体如下:
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)
也可以使用运算符
let date=date()
设Anhorago=日期-时间间隔(3600.0)
苹果文档:
在swift 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
这适用于iOS 13/Swift 5。功劳归于 用法:
var date = Date() // Or any date you wish to convert to text
print("\(date.timeAgoSinceNow())") // "Just Now"
细节
- 代码11.4(11E146),Swift 5.2
NSDate(timeIntervalSinceNow:-3600)
WrapComponents是做什么的?。WrapComponents
意味着如果增加一个小时会使你超过午夜,那么就不要增加一天。我认为使用选项更有意义:[]
,就像线程底部的Deepak答案一样。对于Swift3。。。让alteredDate=userCalendar.date(通过添加:.hour,value:-1,to:now)非常感谢,非常有用!非常有用的答案!这里它是NSDate类的扩展:real Swift 3(+)摆脱NS…
类的建议:让最早的=min(现在,日期)
–让最晚的=max(现在,日期)
–让组件=calendar.dateComponents([.minute、.hour、.day、.weekOfYear、.month、.year、.second],从:最早,到:最晚)
非常感谢……)这个函数对我来说非常有用。选项一,date(通过添加:value:to:wrappingComponents:)
似乎是最合适/最简单的。它允许您向日期添加单个日期组件值。请考虑将您的答案的相关部分格式化为代码。