如何使用日期格式化程序仅显示分钟为零的小时数?

use*_*191 2 swift

我目前使用该格式MM-dd-yyyy HH:mm来显示时间戳。如果时间没有任何分钟组件,是否可以删除分钟?

像,而不是3:00 PM可以只显示3 PM

编辑:

func formatDate(_ dateFormat: String, timeInterval: TimeInterval) -> String {
    let date = Date(timeIntervalSince1970: timeInterval)
    let formatter = DateFormatter()

    formatter.dateFormat = dateFormat
    return formatter.string(from: date) 
}

let formattedDate = formatDate("MM-dd-yyyy HH:mm", timeInterval: 1520422200)
print(formattedDate)
Run Code Online (Sandbox Code Playgroud)

que*_*ful 6

选项1

将 any 替换为返回字符串中的零分钟。

return formatter.string(from: date).replacingOccurrences(of: ":00", with: "")
Run Code Online (Sandbox Code Playgroud)

选项 2

确定是否有分钟,并调整日期格式。

if (Int(timeInterval) % 3600 == 0) {
    let newFormat = dateFormat.replacingOccurrences(of: ":mm", with: "")

    // ...
}
Run Code Online (Sandbox Code Playgroud)