This is the easiest way to create a date object. Now we will be seeing a second way to create the data object i.e. by using Date Formatter. let stringDate = "2019-10-10" let dateFormatter = DateFormatter() dateFormatter. dateFormat = "yyyy-MM-dd" let date = dateFormatter.
dateFormat = "yyyy-MM-dd'T'HH:mm:ss.
Convert Month Day Year String To Date In Swift import Foundation let dateString = "January 20, 2020" let dateFormatter = DateFormatter() dateFormatter. locale = Locale(identifier: "en_US_POSIX") dateFormatter. dateFormat = "MMMM d, yyyy" if let date = dateFormatter.
Swift has its own Date
type. No need to use NSDate
.
In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date
structure. The following would give you the current date and time:
let currentDateTime = Date()
For creating other date-times, you can use one of the following methods.
Method 1
If you know the number of seconds before or after the 2001 reference date, you can use that.
let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM
Method 2
Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date
. For this you can use DateComponents
to specify the components and then Calendar
to create the date. The Calendar
gives the Date
context. Otherwise, how would it know what time zone or calendar to express it in?
// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34
// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)
Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.
Method 3
The most succinct way (but not necessarily the best) could be to use DateFormatter
.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")
The Unicode technical standards show other formats that DateFormatter
supports.
See my full answer for how to display the date and time in a readable format. Also read these excellent articles:
This is best done using an extension to the existing NSDate
class.
The following extension adds a new initializer which will create a date in the current locale using the date string in the format you specified.
extension NSDate
{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
}
Now you can create an NSDate from Swift just by doing:
NSDate(dateString:"2014-06-06")
Please note that this implementation does not cache the NSDateFormatter, which you might want to do for performance reasons if you expect to be creating many NSDate
s in this way.
Please also note that this implementation will simply crash if you try to initialize an NSDate
by passing in a string that cannot be parsed correctly. This is because of the forced unwrap of the optional value returned by dateFromString
. If you wanted to return a nil
on bad parses, you would ideally use a failible initializer; but you cannot do that now (June 2015), because of a limitation in Swift 1.2, so then you're next best choice is to use a class factory method.
A more elaborate example, which addresses both issues, is here: https://gist.github.com/algal/09b08515460b7bd229fa .
extension Date {
init(_ dateString:String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
let date = dateStringFormatter.date(from: dateString)!
self.init(timeInterval:0, since:date)
}
}
Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate
type, e.g:
class Date {
class func from(year: Int, month: Int, day: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: string)!
return date
}
}
Which you can use like:
var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)
Here's how I did it in Swift 4.2:
extension Date {
/// Create a date from specified parameters
///
/// - Parameters:
/// - year: The desired year
/// - month: The desired month
/// - day: The desired day
/// - Returns: A `Date` object
static func from(year: Int, month: Int, day: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return calendar.date(from: dateComponents) ?? nil
}
}
Usage:
let marsOpportunityLaunchDate = Date.from(year: 2003, month: 07, day: 07)
According to Apple documentation
Example :
var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow
In, Swift 3.0 you have set date object for this way.
extension Date
{
init(dateString:String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = Locale(identifier: "en_US_POSIX")
let d = dateStringFormatter.date(from: dateString)!
self(timeInterval:0, since:d)
}
}
Personally I think it should be a failable initialiser:
extension Date {
init?(dateString: String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
if let d = dateStringFormatter.date(from: dateString) {
self.init(timeInterval: 0, since: d)
} else {
return nil
}
}
}
Otherwise a string with an invalid format will raise an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With