我试图得到当前日期之间的差异作为NSDate()和日期从一个PHP时间();调用例如:NSDate(timeintervalsincerely eferencedate: 1417147270)。我怎样才能得到这两个日期之间的时间差呢?我想有一个函数,比较两个日期,如果(秒> 60),那么它返回分钟,如果(分钟> 60)返回小时,如果(小时> 24)返回天,等等。
我该怎么做呢?
编辑:目前接受的答案完全符合我的想法。为了便于使用,我推荐使用它,以便以PHP time()函数使用的形式获取两个日期之间的时间。如果你不是特别熟悉PHP,这是1970年1月1日的时间,单位是秒。这对于PHP的后端是有益的。如果你正在使用像NodeJS这样的后端,你可能会考虑下面的其他选项。
如果有人需要显示所有的时间单位,如“小时分秒”,而不仅仅是“小时”。假设两个日期的时差是1小时59分20秒。该功能将显示“1h 59m 20s”。
下面是我的Objective-C代码:
extension NSDate {
func offsetFrom(date: NSDate) -> String {
let dayHourMinuteSecond: NSCalendarUnit = [.Day, .Hour, .Minute, .Second]
let difference = NSCalendar.currentCalendar().components(dayHourMinuteSecond, fromDate: date, toDate: self, options: [])
let seconds = "\(difference.second)s"
let minutes = "\(difference.minute)m" + " " + seconds
let hours = "\(difference.hour)h" + " " + minutes
let days = "\(difference.day)d" + " " + hours
if difference.day > 0 { return days }
if difference.hour > 0 { return hours }
if difference.minute > 0 { return minutes }
if difference.second > 0 { return seconds }
return ""
}
}
在Swift 3+中:
extension Date {
func offsetFrom(date: Date) -> String {
let dayHourMinuteSecond: Set<Calendar.Component> = [.day, .hour, .minute, .second]
let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: self)
let seconds = "\(difference.second ?? 0)s"
let minutes = "\(difference.minute ?? 0)m" + " " + seconds
let hours = "\(difference.hour ?? 0)h" + " " + minutes
let days = "\(difference.day ?? 0)d" + " " + hours
if let day = difference.day, day > 0 { return days }
if let hour = difference.hour, hour > 0 { return hours }
if let minute = difference.minute, minute > 0 { return minutes }
if let second = difference.second, second > 0 { return seconds }
return ""
}
}
import Foundation
extension DateComponents {
func dateComponentsToTimeString() -> String {
var hour = "\(self.hour!)"
var minute = "\(self.minute!)"
var second = "\(self.second!)"
if self.hour! < 10 { hour = "0" + hour }
if self.minute! < 10 { minute = "0" + minute }
if self.second! < 10 { second = "0" + second }
let str = "\(hour):\(minute):\(second)"
return str
}
}
extension Date {
func offset(from date: Date)-> DateComponents {
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
let differenceOfDate = Calendar.current.dateComponents(components, from: date, to: self)
return differenceOfDate
}
}
Use:
var durationString: String {
return self.endTime.offset(from: self.startTime).dateComponentsToTimeString()
}
——>使用这个找到时间差距在两个日期在Swift(与两个字符串)。
func timeGapBetweenDates(previousDate : String,currentDate : String)
{
let dateString1 = previousDate
let dateString2 = currentDate
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date1 = Dateformatter.date(from: dateString1)
let date2 = Dateformatter.date(from: dateString2)
let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
let secondsInAnHour: Double = 3600
let minsInAnHour: Double = 60
let secondsInDays: Double = 86400
let secondsInWeek: Double = 604800
let secondsInMonths : Double = 2592000
let secondsInYears : Double = 31104000
let minBetweenDates = Int((distanceBetweenDates! / minsInAnHour))
let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))
let monthsbetweenDates = Int((distanceBetweenDates! / secondsInMonths))
let yearbetweenDates = Int((distanceBetweenDates! / secondsInYears))
let secbetweenDates = Int(distanceBetweenDates!)
if yearbetweenDates > 0
{
print(yearbetweenDates,"years")//0 years
}
else if monthsbetweenDates > 0
{
print(monthsbetweenDates,"months")//0 months
}
else if weekBetweenDates > 0
{
print(weekBetweenDates,"weeks")//0 weeks
}
else if daysBetweenDates > 0
{
print(daysBetweenDates,"days")//5 days
}
else if hoursBetweenDates > 0
{
print(hoursBetweenDates,"hours")//120 hours
}
else if minBetweenDates > 0
{
print(minBetweenDates,"minutes")//7200 minutes
}
else if secbetweenDates > 0
{
print(secbetweenDates,"seconds")//seconds
}
}
斯威夫特5
func dateDiff(dateStr:String) -> String {
let f:DateFormatter = DateFormatter()
f.timeZone = NSTimeZone.local
f.dateFormat = "yyyy-M-dd'T'HH:mm:ss.SSSZZZ"
let now = f.string(from: NSDate() as Date)
let startDate = f.date(from: dateStr)
let endDate = f.date(from: now)
var _: NSCalendar = NSCalendar.current as NSCalendar
let dateComponents = Calendar.current.dateComponents([ .weekOfMonth, .day , .hour , .minute , .second], from: startDate!, to: endDate!)
let weeks = abs(dateComponents.weekOfMonth!)
let days = abs(dateComponents.day!)
let hours = abs(dateComponents.hour!)
let min = abs(dateComponents.minute!)
let sec = abs(dateComponents.second!)
var timeAgo = ""
if (sec > 0){
if (sec > 1) {
timeAgo = "\(sec) Seconds Ago"
} else {
timeAgo = "\(sec) Second Ago"
}
}
if (min > 0){
if (min > 1) {
timeAgo = "\(min) Minutes Ago"
} else {
timeAgo = "\(min) Minute Ago"
}
}
if(hours > 0){
if (hours > 1) {
timeAgo = "\(hours) Hours Ago"
} else {
timeAgo = "\(hours) Hour Ago"
}
}
if (days > 0) {
if (days > 1) {
timeAgo = "\(days) Days Ago"
} else {
timeAgo = "\(days) Day Ago"
}
}
if(weeks > 0){
if (weeks > 1) {
timeAgo = "\(weeks) Weeks Ago"
} else {
timeAgo = "\(weeks) Week Ago"
}
}
print("timeAgo is===> \(timeAgo)")
return timeAgo;
}