Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a date only (no time) class in Swift? (or Foundation classes)

Is there a date only (no time) class in Swift? (or Foundation classes)

(as an aside if there is not but there is a well known/popular open-source library that implements this if you could mention this)

EDIT: Updated to clarify with " (or Foundation classes)"

like image 602
Greg Avatar asked Mar 03 '16 11:03

Greg


People also ask

How does date work in Swift?

In Swift, a Date() value encapsulates a single point in time, independent of any particular time zone or calendarical system. To accomplish this, a Date() value is stored as a 64-bit floating point number counting the number of seconds as a relative offset from the reference date of January 1, 2001 at 00:00:00 UTC.

How do I get only time in Swift?

Swift – Get Current Time Only To get only current time, containing hour, minute and second, use Date and DateFormatter . Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only time (hour, minute and second).

What is the date format in Swift?

The date format of the string that is passed to date(from:) method is MM/dd/yy while the dateFormat property has a value of dd/MM/yy .


2 Answers

If you want to get a Date object in Swift 4, like when you are trying to store a Date object in core data, you can use this method.

 private func getDate() -> Date {
let today = Date()

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter .dateStyle = DateFormatter.Style.short

let dateAsString = dateFormatter.string(from: today)

return dateFormatter.date(from: dateAsString)!
}

based on @John R Perry's answer.

like image 198
SajithK Avatar answered Oct 03 '22 00:10

SajithK


Swift 3.0

let date = Date()

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.short

dateFormatter.string(from: date) // 12/15/16
like image 28
John R Perry Avatar answered Oct 02 '22 23:10

John R Perry