0
votes

I am trying to convert 12 digit c# date time ticks formatted time. (648000000000). With the help of following link I added an extension to my code How to get 18-digit current timestamp in Swift?.

extension Date {
    init(ticks: UInt64) {
        self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)
    }
}

let date = Date(ticks: 648000000000)

When I try to see result date it prints following;

0001-01-03 18:00:00 +0000

However, when I try to convert it hour and minute format output is irrelevant like 19:55

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.string(from: date)

My first question is how can I format it to get only 18:00. Second is why it is printing 18:00 when I print only date, but 19:55 when I format it?

2
That method expects "the time since 0001-01-01 measured in 100-nanosecond intervals" – which would be a much larger number (about 18 digits). Where does your timestamp come from, and what date does it represent? - Martin R
That timestamp is coming from our server, I need to convert it somehow, actually I only need clock (18:00) date is not important for our case. @MartinR - atalayasa
I really doubt it's 19:55, because your problem is that print(date) shows you time in UTC/+0 time zone and date formatter is using your current local zone. And minimal timezone offset is multiplier of 1/4 hour, not 5 minutes. - user28434'mstep
Does it help if you add: dateFormatter.timeZone = TimeZone(abbreviation: "UTC") - Bemmu
You should at least have an example of a timestamp AND what date is it representing, and what timezone is the server using. Otherwise it's pure guesswork. And once you know these things, I think you could figure it out on your own, as there are so many examples available online. - Bemmu

2 Answers

2
votes

Apparently your timestamp represents a duration as the number of 100-nanosecond ticks, not a date. If you divide the number by 10^7 then you get the number of seconds. These can be printed as a duration with a DateComponentsFormatter.

Example:

let ticks = 648000000000

let seconds = TimeInterval(ticks) / 10_000_000
let fmt = DateComponentsFormatter()
fmt.allowedUnits = [.hour, .minute]
print(fmt.string(from: seconds)!)

18:00

The duration is 64800 = 18 * 60 * 60 seconds, that are exactly 18 hours.

2
votes

Just don't subtract 62_135_596_800

extension Date {
    init(ticks: UInt64) {
        self.init(timeIntervalSince1970: Double(ticks)/10_000_000)
    }
}

1970-01-01 18:00:00 +0000

The other problem: When you create date and print it, the string is formatted in UTC time zone (offset GMT+0). But DateFormatter returns string representation dependent on its time zone, which is the local timezone by default.

You can fix your code just by setting dateFormatter's timeZone to UTC

dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

18:00