如何获取当前时间作为日期时间 [英] How to get the current time as datetime
问题描述
刚从操场开始。我正在尝试创建一个简单的应用程序。
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
但是我找不到任何属性/方法。我找到了一个方法, dateWithCalendarFormat
。我应该用吗如果是,那么如何?
But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat
. Should I use that? If so, HOW?
推荐答案
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
在objective-c 如何从NSDate获取小时和分钟?
See the same question in objective-c How do I get hour and minutes from NSDate?
与Nate的答案,你会得到这个数字,不是字符串...选择你的选择!
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
这篇关于如何获取当前时间作为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!