Swift
Swift

Reputation: 1182

Time coming wrongly but Date is correct in swift

I am getting date in textfield from datepicker.. in textfield getting correct date and time but from dateFormatter time not coming correctly but date coming perfectly

here is my code

 let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "MM/dd/yy, hh:mm a"
  let dateFormate = dateFormatter.date(from: dateLabel.text!)
    
    print("out put \(dateLabel.text!)")//log out put 8/25/20, 3:40 PM
    print("out put  \(dateFormate)")  // out put  Optional(2020-08-25 10:08:00 +0000)

i am getting correct date but wrong time why?

log out put 8/25/20, 3:40 PM //textfield o/p

out put Optional(2020-08-25 10:08:00 +0000) // dateFormate o/p

where am i mistake, please help me with code.

Upvotes: 0

Views: 598

Answers (2)

Jins George
Jins George

Reputation: 121

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, hh:mm a"
let date = dateFormatter.date(from: (dateLabel.text!))
print(dateFormatter.string(from: date!))

Upvotes: 0

gcharita
gcharita

Reputation: 8357

Based on your requirements, you first need to create a DateFormatter to parse the date string, that you are getting from the dateLabel, to a Date object:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/yy, h:m a"
dateFormatter.locale = Locale(identifier: "in") // here place your locale identifier
let date = dateFormatter.date(from: dateLabel.text!)

and then a new DateFormatter to convert your Date object to the format that you want to print. For example:

let outputDateFormatter = DateFormatter()
outputDateFormatter.dateFormat = "M-d-yyyy, h:m a"
outputDateFormatter.locale = Locale(identifier: "in")
print(outputDateFormatter.string(from: date!))

Upvotes: 1

Related Questions