如何从epoc到今天开始的毫秒数?使用swift

时间:2014-12-19 11:32:55

标签: swift epoch

var timeIntervalSince1970: NSTimeInterval {get}

我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

这将以秒为单位返回时间,如果需要,可以将其更改为返回毫秒数。

var timeIntervalSince1970Seconds: NSTimeInterval {
    return NSDate().timeIntervalSince1970
}
var timeIntervalSince1970MilliSeconds: NSTimeInterval {
    return NSDate().timeIntervalSince1970 * 1000
}

timeIntervalSince1970Seconds       // 1,418,990,057.24468
timeIntervalSince1970MilliSeconds  // 1,418,990,057,246.31

如果您需要从上午12点算起来,可以按照以下步骤进行计算:

extension NSDate {

    var day:    Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay,    fromDate: self).day    }
    var month:  Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth,  fromDate: self).month  }
    var year:   Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear,   fromDate: self).year   }

    var today12am: NSDate {
        return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: 0, minute: 0, second: 0, nanosecond: 0)!
    }
}

var timeIntervalSince1970Sec: NSTimeInterval {
    return NSDate().today12am.timeIntervalSince1970
}
timeIntervalSince1970Sec   // 1,418,954,400.0