Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time as datetime

Tags:

datetime

swift

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?

like image 932
JOSEFtw Avatar asked Jun 05 '14 21:06

JOSEFtw


People also ask

How do I get the current time in Python?

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.

What does datetime datetime NOW () do?

now() function Return the current local date and time, which is defined under datetime module.


1 Answers

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!

like image 112
noliv Avatar answered Oct 08 '22 08:10

noliv