Fab*_*ian 0 nsdateformatter swift
我正在寻找一种方法来使用Swift 3在标签中显示当前日期.目前我正在使用DateFormatter.dateFormat,但我得到的唯一输出是
DD.MM.YYYY
这是代码行:
lbl_Date.text = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "de-AT") as Locale)
Run Code Online (Sandbox Code Playgroud)
我今天的预期产量应该是:
2016年11月12日
我知道我可以通过dateTimeComponents获得时间,但我还没弄明白我如何才能获得标签中的日期(日,月和年):
// get the current date and time
let currentDateTime = Date()
// get the user's calendar
let userCalendar = Calendar.current
// choose which date and time components are needed
let requestedComponents: Set<Calendar.Component> = [
.year,
.month,
.day,
.hour,
.minute,
.second
]
// get the components
let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)
Run Code Online (Sandbox Code Playgroud)
有什么最清晰的方式在我的标签中显示当前日期?
忘记Calendar和DateComponents.使用DateFormatter
let currentDateTime = Date()
let formatter = DateFormatter()
Run Code Online (Sandbox Code Playgroud)
如果要将固定格式设置dateFormat为
formatter.dateFormat = "dd.MM.yyyy"
Run Code Online (Sandbox Code Playgroud)
相反,如果你想根据当前的区域设置的格式timeStyle和dateStyle而非format财产
formatter.timeStyle = .none
formatter.dateStyle = .medium
Run Code Online (Sandbox Code Playgroud)
现在得到字符串
let dateString = formatter.string(from: currentDateTime)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1693 次 |
| 最近记录: |