var millisecondsSince1970: Int64 {
Int64((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds: Int64) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
// Today in milliseconds
Date().millisecondsSince1970 // 1641554695757
// The Date for 1 000 000 000 000 milliseconds
print(Date(milliseconds: 1_000_000_000_000)) // 2001-09-09 01:46:40 +0000
Why am I getting "Expressions are not allowed at the top level" error?
If I understand correctly, this code is inside a class definition or an extension of Date ? Please show complete code, that will make it much easier to help you.
Then, code as
// Today in milliseconds
Date().millisecondsSince1970 // 1641554695757
// The Date for 1 000 000 000 000 milliseconds
print(Date(milliseconds: 1_000_000_000_000)) // 2001-09-09 01:46:40 +0000
must be inside a func, not directly at class level as a declaration.
So you should write:
// Whatever header is…
var millisecondsSince1970: Int64 {
Int64((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds: Int64) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
func displayDates() {
// Today in milliseconds
let dateAsms = Date().millisecondsSince1970 // 1641554695757 Do whatever you need with this
// The Date for 1 000 000 000 000 milliseconds
print(Date(milliseconds: 1_000_000_000_000)) // 2001-09-09 01:46:40 +0000
}