在Swift 3中获取当前日期?

时间:2023-01-24 01:26:33

How can I set label.text current date in Swift 3?

如何设置标签。Swift 3中的当前日期?

I want to print just today to the screen. I did not find how to do that.

我今天想把它打印到屏幕上。我不知道该怎么做。

In c# is very simple:

c#非常简单:

var date = DateTime.Now

I need to write 15.09.2016 in swift 3. thanks

我需要在swift 3上写15.09.2016谢谢

2 个解决方案

#1


181  

You say in a comment you want to get "15.09.2016".

你在评论中说你想获得“15.09.2016”。

For this, use Date and DateFormatter:

为此,使用Date和DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

给格式化程序你想要的格式:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

得到结果字符串:

let result = formatter.string(from: date)

Set your label:

设置你的标签:

label.text = result

Result:

结果:

15.09.2016

15.09.2016

#2


41  

You can do it in this way with Swift 3.0:

你可以通过Swift 3.0这样做:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

#1


181  

You say in a comment you want to get "15.09.2016".

你在评论中说你想获得“15.09.2016”。

For this, use Date and DateFormatter:

为此,使用Date和DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

给格式化程序你想要的格式:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

得到结果字符串:

let result = formatter.string(from: date)

Set your label:

设置你的标签:

label.text = result

Result:

结果:

15.09.2016

15.09.2016

#2


41  

You can do it in this way with Swift 3.0:

你可以通过Swift 3.0这样做:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)