Я занимался исследованиями, но не смог найти точного решения своей проблемы. Я пытался получить 1 час назад от свидания. Как я могу добиться этого в кратчайшие сроки?
Как получить 1 час назад с даты в iOS swift?
Ответ 1
Для правильных вычислений, связанных с 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: [])
Ответ 2
Используйте этот метод и вставьте в свой вспомогательный класс.
Обновление для 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"
}
}
Использование этого метода:
var timeAgo:String=AppHelper.timeAgoSinceDate(date, numericDates: true)
Print("\(timeAgo)") // Ex- 1 hour ago
Ответ 3
Пожалуйста, прочитайте ссылку класса NSDate
.
let oneHourAgo = NSDate.dateWithTimeIntervalSinceNow(-3600)
должен это сделать.
Или для любого объекта NSDate
:
let oneHourBack = myDate.dateByAddingTimeInterval(-3600)
Ответ 4
В соответствии с вашими потребностями вы можете выбрать один из 3 следующих методов Swift 5, чтобы получить один час назад из экземпляра Date
.
1. 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)
2. 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)
3. 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
Ответ 5
Если вы используете NSDate
, вы можете:
let date = NSDate()
date.dateByAddingTimeInterval(-3600)
Он изменит объект date
на "1 час назад".
Ответ 6
Swift3:
let now = Date()
let tempCalendar = Calendar.current
let alteredDate = tempCalendar.date(byAdding: .hour, value: -1, to: now)
Ответ 7
Я создал функциональность, создав расширение 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)
Ответ 8
для 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)
Ответ 9
Вы также можете использовать оператор
let date = Date()
let anHourAgo = date - TimeInterval(3600.0)
Документы Apple: https://developer.apple.com/documentation/foundation/date/2293436