Date to milliseconds and back to date in Swift
I don't understand why you're doing anything with strings...
extension Date {
var millisecondsSince1970:Int64 {
Int64((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int64) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)
Current Date to milliseconds with 10 digits in Swift
You can use this:
let timeStamp = Int(1000 * Date().timeIntervalSince1970)
Convert the current date to time interval (milliseconds since 1970).
You can also use this to check the conversion: https://www.epochconverter.com/
Swift full date with milliseconds
Updated for Swift 3
let d = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:mm:ss.SSSS"
df.string(from: d) // -> "2016-11-17 17:51:15.1720"
When you have a Date
d
, you can get the formatted string using a NSDateFormatter. You can also use a formatter to turn a string date based on your format into a Date
See this chart for more on what dateFormat can do http://waracle.net/iphone-nsdateformatter-date-formatting-table/
Swift - Convert Milliseconds to Date
Update for Swift 3.0:
typealias UnixTime = Int
extension UnixTime {
private func formatType(form: String) -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = form
return dateFormatter
}
var dateFull: Date {
return Date(timeIntervalSince1970: Double(self))
}
var toHour: String {
return formatType(form: "HH:mm").string(from: dateFull)
}
var toDay: String {
return formatType(form: "MM/dd/yyyy").string(from: dateFull)
}
}
var myMilliseconds: UnixTime = 1470075992
print(myMilliseconds.toDay)
How to get Date, Month and Year into Millisecond in swift
Your dateFormat is not match with date. Try below code:
let date:String = "2018-08-04T07:34:15.287Z"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateToConvert = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let finalDate = dateFormatter.string(from: dateToConvert!)
var dateFromString = Date()
if let aString = dateFormatter.date(from: finalDate) {
dateFromString = aString
}
let timeInMiliseconds:Int = Int(TimeInterval(dateFromString.timeIntervalSince1970 * 1000))
You will get 1533321000000 in timeInMiliseconds
You can check time here
How to convert milliseconds to local day, date and time format in swift?
First convert it in date by dividing it by 1000
var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
then use DateFormatter
to convert in desired format you need
Note: Not tested in XCODE
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss"
print(dateFormatter.string(from: date))
Hope it is helpful to you.
DateFormatter: dateFormat milliseconds Swift
Actually it's sufficient to check if the date string contains a period
if dateStr.contains(".") {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ"
} else {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
}
Alternatively use ISO8601DateFormatter
and remove the milliseconds with Regular Expression, this avoids also to specify calendar
, locale
and timezone
let formatter = ISO8601DateFormatter()
let trimmedDateStr = dateStr.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
return formatter.date(from: trimmedDateStr)!
Swift DateFormatter Optional Milliseconds
Two suggestions:
Convert the string with the date format including the milliseconds. If it returns
nil
convert it with the other format.Strip the milliseconds from the string with Regular Expression:
var dateString = "2018-01-21T20:11:20.057Z"
dateString = dateString.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
// -> 2018-01-21T20:11:20Z
Edit:
To use it with Codable
you have to write a custom initializer, specifying dateDecodingStrategy
does not work
struct Foo: Decodable {
let birthDate : Date
let name : String
private enum CodingKeys : String, CodingKey { case born, name }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var rawDate = try container.decode(String.self, forKey: .born)
rawDate = rawDate.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
birthDate = ISO8601DateFormatter().date(from: rawDate)!
name = try container.decode(String.self, forKey: .name)
}
}
let jsonString = """
[{"name": "Bob", "born": "2018-01-21T20:11:20.057Z"}, {"name": "Matt", "born": "2018-01-21T20:11:20Z"}]
"""
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode([Foo].self, from: data)
print(result)
} catch {
print("error: ", error)
}
Related Topics
Choosing the Right iOS Xml Parser
Filemanager Cannot Find Audio File
-[Uiapplication Delegate] Must Be Called from Main Thread Only
How to Save a Uicolor with Userdefaults
Keeping a Uibutton Selected After a Touch
Conversion from Nstimeinterval to Hour,Minutes,Seconds,Milliseconds in Swift
Xcode 7 UI Testing: How to Dismiss a Series of System Alerts in Code
Ios9 - This Application Is Modifying the Autolayout Engine from a Background Thread -- Where
Save Images with Phimagemanager to Custom Album
Can't Assign Multiple Buttons to Uinavigationitem When Using Storyboard with iOS 5
iPhone App Under Test Crashes After a Few Days
Optional Chaining in Swift Closure Where Return Type Has to Be Void
Creating a Reusable Uiview with Xib (And Loading from Storyboard)
How to Use a Uisegmentedcontrol to Switch Views
Class Is Implemented in Both, One of the Two Will Be Used. Which One Is Undefined