Search code examples
iosswiftnsdateformatter

DateFormatter showing different date


I am new to iOS and I want to add some milliseconds say (5) to my date. I have used the below code but I am not getting the exact date which I am using

let str_TimeStamp = "2017-08-09 10:26:30.8"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone

var dateInput: Date? = formatter.date(from: str_TimeStamp)
dateInput = dateInput?.addingTimeInterval(TimeInterval(5*100))
let endtime = formatter.string(from: dateInput!)
print(endtime)

I am getting the output having some delay of mins

2017-08-09 10:28:10.8


Solution

  • The parameter of the addingTimeInterval is the value to add, in seconds.

    So, addingTimeInterval(TimeInterval(5*100)) - adds 500 seconds = 8 minutes.

    If you want to add some milliseconds say (5), you should add this time interval: 0.005

    So, the final code is:

    let str_TimeStamp = "2017-08-09 10:26:30.8"
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
    formatter.timeZone = TimeZone(abbreviation: "UTC")
    
    var dateInput = formatter.date(from: str_TimeStamp)
    dateInput = dateInput?.addingTimeInterval(5/1000)
    
    if let dateInput = dateInput {
        let endtime = formatter.string(from: dateInput)
        print(endtime) // prints 2017-08-09 10:26:30.8050
    }