How do you create a Swift Date object?
Swift has its own Date
type. No need to use NSDate
.
Creating a Date and Time in Swift
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.
Notes
See my full answer for how to display the date and time in a readable format. Also read these excellent articles:
- How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents
- How to work with dates and times in Swift 3, part 2: DateFormatter
- How to work with dates and times in Swift 3, part 3: Date arithmetic
Swift - How to create a date object containing just the time
Let Calendar
do the math, this is more reliable, you aren't using the current date (dateTime
) anyway.
let midnight = Calendar.current.startOfDay(for: Date())
let oneSecondAfterMidnight = Calendar.current.date(byAdding: .second, value: 1, to: midnight)
This works even if midnight doesn't exist due to daylight saving change.
How to get the current time as datetime
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
Making Date With Given Numbers
The function does return the proper date. It's the print
function which displays the date in UTC.
By the way, the native Swift 3 version of your function is
func makeDate(year: Int, month: Int, day: Int, hr: Int, min: Int, sec: Int) -> Date {
var calendar = Calendar(identifier: .gregorian)
// calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let components = DateComponents(year: year, month: month, day: day, hour: hr, minute: min, second: sec)
return calendar.date(from: components)!
}
But if you really want to have UTC date, uncomment the line to set the time zone.
Swift how to init Date
You are getting confused with Date and String, both are different Objects, You can't assign to each other.
There are two solutions to the same
If you want to show exactly the same date that is coming,
import UIKit
struct Post {
var dateString:String!
var Text: String
init(dictionary: [String:Any]) {
self.dateString = dictionary["Date"] as? String
self.Text = dictionary["Text"] as? String ?? ""
}
}ALSO , Label can only Accept String to save
var post: Post? {
didSet {
dateLabel.text = post?.dateString
caprionLabel.text = post?.Text
}
}Save both Date and String in your model
struct Post {
var dateString:String!
var date:Date!
var Text: String
init(dictionary: [String:Any]) {
self.dateString = dictionary["Date"] as? String
let format = DateFormatter()
format.dateFormat = "yyyy-MM/dd HH:mm"
// If dateString doesn't match your date Format Provided
self.date = format.date(from: dateString) ?? Date()
self.Text = dictionary["Text"] as? String ?? ""
}
}ALSO , Label can only Accept String to save
var post: Post? {
didSet {
let format = DateFormatter()
// Assign to any format you want
format.dateFormat = "yyyy-MM/dd HH:mm"
dateLabel.text = format.string(from: post!.date)
caprionLabel.text = post?.Text
}
}
Swift - Getting Date from Month, Day, Year Components
You cannot call date(from
on the type. You have to use an instance of the calendar, either the current
calendar
Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
or a fixed one
let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
Creating a Date Object in Swift With Just a Weekday and an Hour
(NS)Date
represents an absolute point in time and knows nothing about weekdays, hours, calendar, timezones etc. Internally it is represented
as the number of seconds since the "reference date" Jan 1, 2001, GMT.
If you are working with EventKit
then EKRecurrenceRule
might be
better suited. It is a class used to describe the recurrence pattern for a recurring event.
Alternatively, store the event just as a DateComponentsValue
, and
compute a concrete Date
when necessary.
Example: A meeting every Monday at 8 PM:
let meetingEvent = DateComponents(hour: 20, weekday: 2)
When is the next meeting?
let now = Date()
let cal = Calendar.current
if let nextMeeting = cal.nextDate(after: now, matching: meetingEvent, matchingPolicy: .strict) {
print("now:", DateFormatter.localizedString(from: now, dateStyle: .short, timeStyle: .short))
print("next meeting:", DateFormatter.localizedString(from: nextMeeting, dateStyle: .short, timeStyle: .short))
}
Output:
now: 21.11.16, 20:20
next meeting: 28.11.16, 20:00
Convert string to date in Swift
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)Finally create a new
Date
object and strip minutes and secondslet finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
Related Topics
What Is an "Unwrapped Value" in Swift
iOS Uitextview or Uilabel with Clickable Links to Actions
iOS Application Executing Tasks in Background
Cut Transparent Hole in Uiview
How to Downgrade or Install an Older Version of Cocoapods
Resizing Uitableview to Fit Content
How to Correctly Linearize Depth in Opengl Es in Ios
Create Uiimage With Solid Color in Swift
Manual Language Selection in an Ios-App (Iphone and Ipad)
Detecting Sheet Was Dismissed on iOS 13
Nsurlconnection and Basic Http Authentication in Ios
Programmatically Create a Uiview With Color Gradient
Xcode 9 Error: "Iphone Has Denied the Launch Request"
Cgcontextdrawimage Draws Image Upside Down When Passed Uiimage.Cgimage
Importing Project-Swift.H into a Objective-C Class...File Not Found
How to Make App Fully Working Correctly for Autorotation in iOS 6