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 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"
Get All Hours of The Day (in date format) from 9am tp 11pm and Save within an array in Swift
When you access .hour for any calender its in a 24h format. so you need to something like this:
let today = Date()
var sortedTime: [Date] = []
var calender = Calendar(identifier: .iso8601)
calender.locale = Locale(identifier: "en_US_POSIX")
let currentHour = calender.component(.hour, from: today)
(0...(24-currentHour)).forEach {
guard let newDate = calender.date(byAdding: .hour, value: $0, to: today) && calender.component(.hour, from: newDate) != 0,
calender.component(.hour, from: newDate) <= 23 else {
return
}
//convert date into desired format
sortedTime.append(newDate)
}
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.
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.
Display time of day when a button is pressed ios
You need to use DateFormatter
instead of DateComponents
to get Date
or Time
in specific format.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let time = dateFormatter.string(from: Date())
mylable.text = time
How to calculate Day(s) and Hour(s) remaining in swift between two dates?]
Try using DateFormatter
and DateComponents
to get this working.
Get the Date
instances from String
using DateFormatter
and then get day
and hour
components using DateComponents
, i.e.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let d1 = dateFormatter.date(from: "2019-11-23"), let d2 = dateFormatter.date(from: "2019-11-4") {
let components = Calendar.current.dateComponents([.day, .hour], from: d2, to: d1)
print(components.day, components.hour)
}
How to get 1 hour ago from a date in iOS swift?
For correct calculations involving NSDate that take into account all edge cases of different calendars (e.g. switching between day saving time) you should use NSCalendar class:
Swift 3+
let earlyDate = Calendar.current.date(
byAdding: .hour,
value: -1,
to: Date())
Older
// Get the date that was 1hr before now
let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Hour,
value: -1,
toDate: NSDate(),
options: [])
Related Topics
Invalid Signature - Code Object Is Not Signed at All
Randomly Choosing an Item from a Swift Array Without Repeating
MySQL and Swift - Upload Image and File || Would It Be Better to Use Alamofire
How to Count Rows in a Parse Class Programmatically in an iOS App Using Swift
How to Make a Call Which Begin with * in Iphone
How to Analyze Stack Trace Info of a Thread
How to Run Timer Though the App Entered Background or Is Terminated
How to Intercept Push Notifications for Another App
How to Parse This JSON in Swift
Why I Couldn't Assign Fetched Values from Firestore to an Array in Swift
How to Force My Keyboard to Be Up on My Program's Start in Swift
How to Use Device Instead of Simulator
No Such File and Directory Found Xcode 7
How to Fetch User's Email Using Facebook
What Is the Meaning of This Declaration
How to Change Height of Uitableviewcell Real-Time
iOS Bar Item Image Displaying Wrong Color
Xcode Instruments Allocations: Look at Live Bytes or Overall Bytes