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 add 5 minutes to my current time
Try this
let calendar = Calendar.current
let date = calendar.date(byAdding: .minute, value: 3, to: Date())
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
var selectedTime = dateFormatter.string(from: date!)
How to add minutes to custom time in swift2
You need to use dateByAddingUnit
as @Rob doing instead of dateByAddingTimeInterval
. The reason you are not getting correct time is may because of TimeZone
so try to set timeZone
with your NSDateFormatter
instance.
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
//Now add the 3 minute in endTime
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])
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 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.
Adding Time Interval. e.g hours, minutes and seconds
I’m going to assume that “01:32:34” represents an elapsed time of 5,554 seconds, not 1:32am. So, I’d convert it to a TimeInterval
, not a Date
:
func timeInterval(from string: String) -> TimeInterval? {
let components = string.components(separatedBy: ":").map { Double($0) }
guard
components.count == 3,
let hours = components[0],
let minutes = components[1],
let seconds = components[2]
else { return nil }
return ((hours * 60) + minutes) * 60 + seconds
}
You can chose to store either the original “01:32:34” string or this value, 5,554.0.
Anyway, then adding these numeric time intervals is trivial addition. And to display a resulting TimeInterval
, you’d use a DateComponentsFormatter
, e.g.
let timeIntervalFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute, .second]
return formatter
}()
func totalElapsed(_ strings: [String]) -> String? {
let total = strings.reduce(TimeInterval.zero) { sum, string in
sum + (timeInterval(from: string) ?? 0)
}
return timeIntervalFormatter.string(from: total)
}
let strings = ["1:15:16", "00:15:02", "00:45:27"]
let result = totalElapsed(strings)
02:15:45
Or if you want more of a (localized) natural language representation, use unitsStyle
of .full
:
2 hours, 15 minutes, 45 seconds
This approach (using TimeInterval
, not Date
) has the virtue that it also can represent intervals that exceed 24 hours.
SWIFT: How do I add hours to NSDate object
You're asking the wrong question. This is what's known as an "XY Problem".
You should be asking "How do I display a date string I get from a web server in the user's local time zone."
NSDate
represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.
The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let date = dateFormatter.dateFromString(dateFromService)
let outputDatedateFormatter = NSDateFormatter()
outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//leave the time zone at the default (user's time zone)
let displayString = outputDateFormatter.stringFromDate(date)
println("Date in local time zone = \(displayString)")
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.
Related Topics
How to Access Own Window Within Swiftui View
Make a Uibutton Programmatically in Swift
Uigraphicsgetimagefromcurrentimagecontext Memory Leak with Previews
Xcode Nsmanagedobject Subclass Contains Optionals When They Are Marked as Non-Optional
Getting User Location Every N Minutes After App Goes to Background
Get Image from Documents Directory Swift
How to Convert a Double into a Byte Array in Swift
Arkit - Apply Cifilter to a Specific Vertices of Arfaceanchor
Loading a Reusable Uitableviewcell from a Nib
Change Status Bar Background Color in Swift 3
iOS Universal Device App with Spritekit, How to Scale Nodes for All Views
Kcfstreamerrordomainssl, -9802 When Connecting to a Server by Ip Address Through Https in iOS 9
Select Multiple Images (Uiimagepickercontroller or Photos.App Share Ui)
Scroll Uitextfield Above Keyboard in a Uitableviewcell on a Regular Uiviewcontroller