How to change the current day's hours and minutes in Swift?
Be aware that for locales that uses Daylight Saving Times, on clock change days, some hours may not exist or they may occur twice. Both solutions below return a Date?
and use force-unwrapping. You should handle possible nil
in your app.
Swift 3, 4, 5 and iOS 8 / OS X 10.9 or later
let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!
Swift 2
Use NSDateComponents
/ DateComponents
:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)
// Change the time to 9:30:00 in your locale
components.hour = 9
components.minute = 30
components.second = 0
let date = gregorian.dateFromComponents(components)!
Note that if you call print(date)
, the printed time is in UTC. It's the same moment in time, just expressed in a different timezone from yours. Use a NSDateFormatter
to convert it to your local time.
How to calculate days, hours, minutes from now to certain date in swift
You need to find out when is the next birth date based on the day and month of birthday. You can use Calendar's method nextDate(after: Date, matching: DateComponents)
func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
let birthDateCoponents = DateComponents(month: 4, day: 16)
let nextBirthDate = Calendar.current.nextDate(after: Date(), matching: birthDateCoponents, matchingPolicy: .nextTime)!
let difference = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: nextBirthDate)
difference.day // 105
difference.hour // 2
difference.minute // 5
difference.second // 30
When displaying it to the user you can use DateComponentsFormatter with the appropriate unitsStyle
. You can see below how it would look like when using .full
style and limiting the units to .day, .hour, .minute, .second
:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute, .second]
formatter.unitsStyle = .full
formatter.string(from: Date(), to: nextBirthDate) // "105 days, 1 hour, 44 minutes, 36 seconds"
How to add minutes to current time in swift
Two approaches:
Use
Calendar
anddate(byAdding:to:wrappingComponents:)
. E.g., in Swift 3 and later:let calendar = Calendar.current
let date = calendar.date(byAdding: .minute, value: 5, to: startDate)Just use
+
operator (see+(_:_:)
) to add aTimeInterval
(i.e. a certain number of seconds). E.g. to add five minutes, you can:let date = startDate + 5 * 60
(Note, the order is specific here: The date on the left side of the
+
and the seconds on the right side.)You can also use
addingTimeInterval
, if you’d prefer:let date = startDate.addingTimeInterval(5 * 60)
Bottom line, +
/addingTimeInterval
is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval
doesn’t.
For Swift 2 renditions, see the previous revision of this answer.
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!
How to get hours and minutes from UIDatePicker
UIDatePicker
just give you the selected Date
, if you need the date component based on current calendar, check out the Calendar
and DateComponent
documendation for details.
let now = Date() // your date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: now)
dateComponents.hour
dateComponents.minute
If you need hours
and minutes
for time distance, you need the calculate it manually with your prefer base date.
Swift Calendar Date By Setting Hour To 0 Changes Day
I think this is expected as it says in the documentation,
The algorithm will try to produce a result which is in the next-larger
component to the one given (there’s a table of this mapping at the top
of this document). So for the “set to Thursday” example, find the
Thursday in the Week in which the given date resides (which could be a
forwards or backwards move, and not necessarily the nearest Thursday).
For more control over the exact behavior, use
nextDate(after:matching:matchingPolicy:behavior:direction:).
Using nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
yields correct result as you would expect.
Example is here,
let calendar = Calendar.current
var hourComponent = DateComponents()
hourComponent.hour = 0
let midnightSameDay = calendar.nextDate(after: date,
matching: hourComponent,
matchingPolicy: .nextTime,
direction: .backward)
print(mightnightSameDay) // 2018-04-19 00:00:00 +0000
let midnightNextDay = calendar.nextDate(after: date,
matching: hourComponent,
matchingPolicy: .nextTime,
direction: .forward)
print(mightnightNextDay) // 2018-04-20 00:00:00 +0000
And there is yet another method that you could use for this which uses search direction and matching policy,
let midnightSameDay = calendar.date(bySettingHour: 0,
minute: 0,
second: 0,
of: date,
direction: .backward)
Related Topics
Converting Url to String and Back Again
Default Optional Parameter in Swift Function
What Is the Swift Equivalent of -[Nsobject Description]
Animate Cell When Pressed Using Swift 3
How to Print Call Stack in Swift
Why Is the Alert Triggering Out of Order If Value Is Not Updated
Swift - Force Synchronous Execution of Work and Subsequent UI Rendering
How to Bring Nswindow to Front and to the Current Space
How to Convert Anyclass to a Specific Class and Init It Dynamically in Swift
How to Change Navigationbar Font in Swift
What's the Best Way to Cut Swift String into 2-Letter-Strings
How to Query Nested Data in Firebase Database
Expand and Contract Tableview Cell When Tapped, in Swift
Swift Encode Tuple Using Nscoding
Is There a Preferred Technique to Prohibit Pasting into a Uitextfield