Just started with the playground. I'm trying to create a simple app.
I've created a date object like this:
var date = NSDate()
How can I get the current hour? In other languages I can do something like this:
var hour = date.hour
But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat
. Should I use that? If so, HOW?
You can use the below code snippet to get the current time in python. First, use the datetime. now() from the DateTime library and then format it using the strftime("%H:%M:%S") to get only the time information. When you print the current_time object, you'll see the current time in the 24H format as shown below.
now() function Return the current local date and time, which is defined under datetime module.
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!
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