Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在swift中查找当前月份名称和当前月份编号_Ios_Swift_Date_Swift4 - Fatal编程技术网

Ios 如何在swift中查找当前月份名称和当前月份编号

Ios 如何在swift中查找当前月份名称和当前月份编号,ios,swift,date,swift4,Ios,Swift,Date,Swift4,我想知道swift中的当前月号是int,名称是string。有人能帮我简单的代码吗?你可以使用DateFormatter获取当前月的名称,使用Calendar的组件获取当前月的索引 let currentDate = Date() let nameFormatter = DateFormatter() nameFormatter.dateFormat = "MMMM" // format January, February, March, ... let name = nameFormatt

我想知道swift中的当前月号是int,名称是string。有人能帮我简单的代码吗?

你可以使用
DateFormatter
获取当前月的名称,使用
Calendar
组件
获取当前月的索引

let currentDate = Date()

let nameFormatter = DateFormatter()
nameFormatter.dateFormat = "MMMM" // format January, February, March, ...

let name = nameFormatter.string(from: currentDate)
let index = Calendar.current.component(.month, from: currentDate) // format 1, 2, 3, ...

print(name)  // April
print(index) // 4

您可以获得的当前日期的编号如下所示:

let monthAsNr = Calendar.current.component(.month, from: Date())
或:


这个答案实际上没有回答OP关于获取月份索引及其名称的问题。这是一个非常糟糕的问题,缺乏研究,要求我们做所有的工作。如果让我们来做,就不需要
。只需执行
monthInt=Calendar.current.dateComponents([.month],from:Date()).month。强制展开
月份
是安全的,因为您特别要求该组件。
if let monthInt = Calendar.current.dateComponents([.month], from: Date()).month {
    let monthStr = Calendar.current.monthSymbols[monthInt-1]
    print(monthInt) // 4
    print(monthStr) // April
}
let monthInt = Calendar.current.component(.month, from: Date()) // 4
let monthStr = Calendar.current.monthSymbols[monthInt-1] // April