Zeona
Zeona

Reputation: 454

How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift?

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I can extract the same in string format but I want to get this in Date format. Here is my sample code.

let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)

//date - 2018-09-28 //updateDate - 2018-09-28 09:42:00 +0000

Upvotes: 0

Views: 719

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236305

You can simply get your date string prefix 11 and insert noon time when parsing your string:

let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"

if let date = df.date(from: str.prefix(11) + "12:00") {
    print(date.description(with: .current))
}

// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Upvotes: 1

Related Questions