Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change time format from string in Swift 3.0

Tags:

time

format

swift

i have a string like "22:02:20" and need to format it to "10:02:00" i have try this:

    let time = "22:02:00"

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm:ss"


    let calendar = Calendar.current
    let unitFlags = Set<Calendar.Component>([.hour, .minute])

    staticHoraInicio = calendar.dateComponents(unitFlags, from: dateFormatter.date(from: time))

but i get 22 and 2, how can i get 10 and 02. Also i try:

let horaF = dateFormatter.date(from: time!)

but i get something like "2000-01-02 03:00:00 +0000", ¿there is a way to format just a time string without date?

I need this to store a start time and end time coming from a DB, compare it to the current time to get if it's between, some example about how to do this???

like image 529
Alejandro Henriquez Avatar asked Dec 14 '22 01:12

Alejandro Henriquez


1 Answers

let time = "22:02:00"

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "HH:mm:ss"

var fullDate = dateFormatter.date(from: time)

dateFormatter.dateFormat = "hh:mm:ss a"

var time2 = dateFormatter.string(from: fullDate!)
like image 121
Vijay Ladva Avatar answered Dec 16 '22 15:12

Vijay Ladva