ios 如何从iOS swift中的日期获得1小时前?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27251644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:52:09  来源:igfitidea点击:

How to get 1 hour ago from a date in iOS swift?

iosiphoneswiftdate

提问by saksut

I have been researching, but I couldnt find exact solution for my problem. I have been trying to get 1 hour ago from a date. How can I achieve this in swift?

我一直在研究,但我无法为我的问题找到确切的解决方案。我一直试图从约会中获得 1 小时前。我怎样才能快速实现这一目标?

回答by Vladimir

For correct calculations involving NSDate that take into account all edge cases of different calendars (e.g. switching between day saving time) you should use NSCalendar class:

对于考虑到不同日历的所有边缘情况的 NSDate 的正确计算(例如在日间节省时间之间切换),您应该使用 NSCalendar 类:

Swift 3+

斯威夫特 3+

let earlyDate = Calendar.current.date(
  byAdding: .hour, 
  value: -1, 
  to: Date())

Older

年长的

// Get the date that was 1hr before now
let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(
       .Hour,
       value: -1, 
       toDate: NSDate(),
       options: [])

回答by Sourabh Sharma

Use this method and paste in your helper class.

使用此方法并粘贴到您的助手类中。

Update for Swift 3 and XCode 8.3

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"
    }

}

Use of this method:

这种方法的使用:

var timeAgo:String=AppHelper.timeAgoSinceDate(date, numericDates: true)
Print("\(timeAgo)")   // Ex- 1 hour ago

回答by zisoft

Please read the NSDateclass reference.

请阅读NSDate类参考。

let oneHourAgo = NSDate.dateWithTimeIntervalSinceNow(-3600)

should do it.

应该这样做。

Or, for any NSDateobject:

或者,对于任何NSDate对象:

let oneHourBack = myDate.dateByAddingTimeInterval(-3600)

Swift 4:

斯威夫特 4:

let oneHourAgo = NSDate(timeIntervalSinceNow: -3600)

回答by Imanou Petit

According to your needs, you may choose one of the 3 following Swift 5 methods to get one hour ago from a Dateinstance.

根据您的需要,您可以选择以下 3 种 Swift 5 方法之一从Date实例中获取一小时前。



1. date(byAdding:value:to:wrappingComponents:)

1. date(byAdding:value:to:wrappingComponents:)

Calendarhas a method called date(byAdding:value:to:wrappingComponents:). date(byAdding:value:to:wrappingComponents:)has the following declaration:

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?

Returns a new Daterepresenting the date calculated by adding an amount of a specific component to a given date.

返回一个新的Date表示通过将特定组件的数量添加到给定日期计算出的日期。

The Playground code below shows how to use it:

下面的 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:)

2. date(byAdding:to:wrappingComponents:)

Calendarhas a method called date(byAdding:to:wrappingComponents:). date(byAdding:value:to:wrappingComponents:)has the following declaration:

Calendar有一个方法叫做date(byAdding:to:wrappingComponents:). date(byAdding:value:to:wrappingComponents:)有以下声明:

func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = default) -> Date?

Returns a new Daterepresenting the date calculated by adding components to a given date.

返回一个新的Date表示通过向给定日期添加组件计算出的日期。

The Playground code below shows how to use it:

下面的 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)

Alternative:

选择:

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(_:)(use with caution)

3. addingTimeInterval(_:)(慎用)

Datehas a method called addingTimeInterval(_:). addingTimeInterval(_:)has the following declaration:

Date有一个方法叫做addingTimeInterval(_:). addingTimeInterval(_:)有以下声明:

func addingTimeInterval(_ timeInterval: TimeInterval) -> Date

Return a new Dateby adding a TimeIntervalto this Date.

Date通过向TimeIntervalthis 中添加 a来返回一个新的Date

Note that this method comes with a warning:

请注意,此方法带有警告:

This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a Calendar. That will take into account complexities like daylight saving time, months with different numbers of days, and more.

这仅调整绝对值。如果您想添加日历概念,如小时、天、月,则必须使用Calendar. 这将考虑到诸如夏令时、具有不同天数的月份等复杂性。

The Playground code below shows how to use it:

下面的 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

回答by kbagi

If you are using NSDateyou can do:

如果您正在使用,NSDate您可以执行以下操作:

let date = NSDate()
date.dateByAddingTimeInterval(-3600)

It will change the dateobject to be "1 hour ago".

它会将date对象更改为“1 小时前”。

回答by Chris Allinson

Swift3:

斯威夫特3:

let now = Date()
let tempCalendar = Calendar.current
let alteredDate = tempCalendar.date(byAdding: .hour, value: -1, to: now)

回答by H S Progr

I achieve time ago functionality by creating extension of Date. Which is given below:

我通过创建日期的扩展来实现时间前功能。下面给出:

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 ""
  }
}

Then i get the time ago by calculating the difference between current date and specified date:

然后我通过计算当前日期和指定日期之间的差异来获得时间:

   let timeAgo = Date().timeAgo(from: sender.date)

回答by coco

You can also use an operator

您还可以使用运算符

let date = Date()
let anHourAgo = date - TimeInterval(3600.0)

Apple Docs: https://developer.apple.com/documentation/foundation/date/2293436

苹果文档:https: //developer.apple.com/documentation/foundation/date/2293436

回答by Deepak Sharma

for Swift 2:

对于 Swift 2:

extension NSDate {
    func after(value: Int, calendarUnit:NSCalendarUnit) -> NSDate {
        return calendar.dateByAddingUnit(calendarUnit, value: value, toDate: self, options: [])!
    }
}

how to use:

如何使用:

let lastHour = NSDate().after(-1, calendarUnit: .Hour)

回答by Enamul Haque

In swift 5 You can use

在 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!)

Out put will Be like bellow

输出将像波纹管

Current DateTime--> 2019-12-20 09:40:08
One Hour Previous Date Time--> 2019-12-20 08:40:08