以特定格式获取当前日期

时间:2020-07-09 07:06:55

标签: ios swift

我知道要获取当前时间,您要做的就是声明一个这样的变量:

var currentTime = Date()
print(currentTime)

将打印类似2020-07-09 07:00:00 +0000

是否有这样的方式可以以一种特定的格式获取当前时间,而仍然保持日期类型?

例如,对于上述2020-07-09 07:00:00 +0000 相反,我想获得2020-07-08 15:00:00 +0000

1 个答案:

答案 0 :(得分:-1)

解决问题,您需要熟悉DateFormatter。日期格式化程序可帮助您以任何喜欢的方式格式化日期。

查看此代码。这应该可以实现您想要的:

// Foundation provides the functionality for the code below (included in UIKit)
import Foundation

// Create a new date object for the current date
let date = Date()

// Create a new date formatter and set its date format --> check out different dateFormat Codes below
let formatter = DateFormatter()
formatter.dateFormat = "eeee, dd.MM"

// Convert the created date by using your date formatter.
let formattedDateString = formatter.string(for: Date())

查看一些常用格式:

Wednesday, Sep 12, 2018           --> EEEE, MMM d, yyyy
09/12/2018                        --> MM/dd/yyyy
09-12-2018 14:11                  --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM                   --> MMM d, h:mm a
September 2018                    --> MMMM yyyy
Sep 12, 2018                      --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000   --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000          --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18                          --> dd.MM.yy
10:41:02.112                      --> HH:mm:ss.SSS

希望这对您有帮助!

相关问题