简体   繁体   中英

How to convert the System Date into date format into Date Datatype

I want to convert the current date with the help of the DateFormatter into Date datatype. I want the date to be in dd/mm/yyyy format and its datatype should be Date not string. Here's the code I've tried and the output i am getting.

let date = Date()
print(date)//output - 2017-02-24 13:39:01 +0000
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let tempDate = dateFormatter.string(from: date)
print(tempDate)//output - 24/02/2017
let currentDate = dateFormatter.date(from: tempDate)
print(currentDate!)//output - 2017-02-23 18:30:00 +0000

If you expect that the output of print(currentDate!) equals 2017-02-24 00:00:00 +0000 set the dateFormatter timeZone to GMT

dateFormatter.timeZone = TimeZone(secondsFromGMT:0)

Update

I think that I understood your need. You want to truncate time from a Date object.

let date = Date()
print(date)
let calendar = NSCalendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let currentdate = calendar.date(from: components)
print(currentdate!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM