Chris
Chris

Reputation: 105

How to store a time interval with HH:MM:SS:MS swift

So this turned out to be way more complex than I was I expecting. I have four text fields that allows the user to enter HH:MM:SS:MS and I need to mash these together to create a number I can save in fireStore.

I then need to get this number out and convert it back to HH:MM:SS:MS again for use in a tables graphs etc.

I did initially consider using a string but that's not going to help me with graphs/ordering I want to do later. Done a lot of searching and haven't been able to find a workable solution that includes milliseconds.

Any help appreciated!

Some code below if that helps, all I have at the moment is me mashing these together into a string...

let goalHHText = UITextField()
let goalMMText = UITextField()
let goalSSText = UITextField()
let goalMSText = UITextField()

let goalCombined.append(goalHHText.text! + ":" + goalMMText.text! + ":" + goalSSText.text! + ":" + goalMSText.text!)

I'm then adding goalCombined into a dictionary and pushing into Firestore. Sorry that's as far as I've got, I am 100% coding noob.

I've looked at dateComponentsFormatter but that doesn't support milliseconds

let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second ]
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)

Upvotes: 0

Views: 689

Answers (1)

Haris Wilson
Haris Wilson

Reputation: 166

Convert it into smallest unit time, here milliseconds. Convert the entire time to milliseconds by :-

index = (((HH*60 + MM)*60 + SS)*60 + MS)*1000;

Store 'index' value in firestore as type "number". Also store individual HH, MM, SS, MS values separately in firestore for easy retrieval.

Upvotes: 2

Related Questions