最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift中获取两个日期时间之间的间隔差

Swift crifan 3943浏览 0评论

swift nsdate interval

Finding the difference in time between two NSDates Swift – Stack Overflow

ios – Getting the difference between two NSDates in (months/days/hours/minutes/seconds) – Stack Overflow

可以用:

let interval:NSTimeInterval = curTimestamp.timeIntervalSinceDate(prevTimestamp!)

最后完整的代码如下:

//: Playground – noun: a place where people can play
import UIKit
extension NSDate
{
    //2015
    func Year() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentYear:Int = curCalendar.component(NSCalendarUnit.Year, fromDate: self)
        return componentYear
    }
   
    //11
    func Month() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentMonth:Int = curCalendar.component(NSCalendarUnit.Month, fromDate: self)
        return componentMonth
    }
   
    //28
    func Day() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentDay:Int = curCalendar.component(NSCalendarUnit.Day, fromDate: self)
        return componentDay
    }
   
    //10
    func Hour() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentHour:Int = curCalendar.component(NSCalendarUnit.Hour, fromDate: self)
        return componentHour
    }
   
    //39
    func Minute() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentMinute:Int = curCalendar.component(NSCalendarUnit.Minute, fromDate: self)
        return componentMinute
    }
   
    //18
    func Second() -> Int {
        let curCalendar:NSCalendar = NSCalendar.currentCalendar()
        let componentSecond:Int = curCalendar.component(NSCalendarUnit.Second, fromDate: self)
        return componentSecond
    }
   
    //get short style date time string
    //11/28/15, 10:51 AM
    func toStringShort() -> String {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        let shortStyleStr:String = dateFormatter.stringFromDate(self)
        return shortStyleStr
    }
   
    //get medium style date time string
    //Nov 28, 2015, 10:51:33 AM
    func toStringMedium() -> String {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
        let mediumStyleStr:String = dateFormatter.stringFromDate(self)
        return mediumStyleStr
    }
   
    //get long style date time string
    //November 28, 2015 at 10:51:33 AM GMT+8
    func toStringLong() -> String {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.LongStyle
        let longStyleStr:String = dateFormatter.stringFromDate(self)
        return longStyleStr
    }
   
    //get full style date time string
    //Saturday, November 28, 2015 at 10:51:33 AM China Standard Time
    func toStringFull() -> String {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.FullStyle
        let fullStyleStr:String = dateFormatter.stringFromDate(self)
        return fullStyleStr
    }
   
    //get date formatted string
    //2015/11/28 10:48:12
    func toString(dateFormat:String) -> String {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = dateFormat
        let formattedDatetimeStr:String = dateFormatter.stringFromDate(self)
        return formattedDatetimeStr
    }
   
    //parse input date time string into NSDate
    //input: 2015/11/28 12:01:02 and yyyy/MM/dd HH:mm:ss
    //output: Optional(2015-11-28 04:01:02 +0000)
    static func fromString(datetimeStr:String, dateFormat:String) -> NSDate? {
        let dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = dateFormat
        let parsedDatetime:NSDate? = dateFormatter.dateFromString(datetimeStr)
        return parsedDatetime
    }
   
    //from milli second timestamp to NSDate
    static func fromTimestampMsec(timestampInt64InMsec:Int64) -> NSDate {
        //        print("timestampInt64InMsec=\(timestampInt64InMsec)") //timestampInt64InMsec=1449805150184
        let timestampDoubleInSec:Double = Double(timestampInt64InMsec)/1000
        //        print("timestampDoubleInSec=\(timestampDoubleInSec)") //timestampDoubleInSec=1449805150.184
        let parsedDate:NSDate = NSDate(timeIntervalSince1970: NSTimeInterval(timestampDoubleInSec))
        //        print("parsedDate=\(parsedDate)") //parsedDate=2015-12-11 03:39:10 +0000
       
        return parsedDate
    }
   
}
func generateTimestampStr(prevTimestamp:NSDate?, curTimestamp:NSDate) -> String {
    //let timestampStr = timestamp.toString("yy/MM/dd HH:mm:ss")
    //    let timestampStr = timestamp.toString("HH:mm:ss")
    var curTimestampStr:String = ""
   
    if prevTimestamp == nil {
        curTimestampStr = curTimestamp.toString("yyyy/MM/dd HH:mm")
       
        return curTimestampStr
    }
   
    let prevOneDayInterval:NSTimeInterval = NSTimeInterval(-60*60*24)
    let fiveMinutesInterval:NSTimeInterval = NSTimeInterval(5*60)
    /*
    上下两条时间差在5分钟以内,不显示时间
    上下两条差1天以内,显示发送时间,不用日期
    上下两条差3天以内,显示昨天/前天+发送时间
    上下两条差3天以上,显示日期+发送时间
    */
    let today:NSDate = NSDate()
    print("today=\(today)")
    let yestoday:NSDate = today.dateByAddingTimeInterval(prevOneDayInterval)
    print("yestoday=\(yestoday)")
    let dayBeforeYestoday:NSDate = yestoday.dateByAddingTimeInterval(prevOneDayInterval)
    print("dayBeforeYestoday=\(dayBeforeYestoday)")
   
    let interval:NSTimeInterval = curTimestamp.timeIntervalSinceDate(prevTimestamp!)
   
    if interval < fiveMinutesInterval {
        //within 5 minutes, not show timestamp
        curTimestampStr = ""
    } else {
        if curTimestamp.Year() == today.Year() {
            //same year
            if (curTimestamp.Month() == today.Month()) && (curTimestamp.Day() == today.Day()) {
                //today
                curTimestampStr = curTimestamp.toString("HH:mm")
            } else if (curTimestamp.Month() == yestoday.Month()) && (curTimestamp.Day() == yestoday.Day()) {
                curTimestampStr = curTimestamp.toString("昨天 HH:mm")
            } else if (curTimestamp.Month() == dayBeforeYestoday.Month()) && (curTimestamp.Day() == dayBeforeYestoday.Day()) {
                curTimestampStr = curTimestamp.toString("前天 HH:mm")
            } else {
                curTimestampStr = curTimestamp.toString("MM/dd HH:mm")
            }
        } else {
            //not same year
            curTimestampStr = curTimestamp.toString("yyyy/MM/dd HH:mm")
        }
    }
    print("prevTimestamp=\(prevTimestamp), curTimestamp=\(curTimestamp) -> curTimestampStr=\(curTimestampStr)")
   
    return curTimestampStr
}
//let prevTimestamp = NSDate.fromString("2015/11/28 12:01:02", dateFormat: "yyyy/MM/dd HH:mm:ss")!
//let curTimestamp = NSDate.fromString("2016/01/01 12:01:02", dateFormat: "yyyy/MM/dd HH:mm:ss")!
let prevTimestamp = NSDate.fromString("2015/01/28 12:01:02", dateFormat: "yyyy/MM/dd HH:mm:ss")!
let curTimestamp = NSDate.fromString("2015/02/15 11:37:02", dateFormat: "yyyy/MM/dd HH:mm:ss")!
generateTimestampStr(nil, curTimestamp:curTimestamp)
//generateTimestampStr(prevTimestamp, curTimestamp:curTimestamp)
//var today:NSDate = NSDate()
////let yestoday:NSDate = today.dateByAddingTimeInterval(-3600*24*365)
//let yestoday:NSDate = today.dateByAddingTimeInterval(-3600*24)
//let dayBeforeYestoday = yestoday.dateByAddingTimeInterval(-3600*24)

转载请注明:在路上 » [已解决]swift中获取两个日期时间之间的间隔差

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
91 queries in 0.210 seconds, using 22.33MB memory