当前位置: 首页 > 工具软件 > SwiftDate > 使用案例 >

Swift Date转String

东郭赞
2023-12-01

在Swift3.0下

1.获取当前时间并转成字符串

func dateNowAsString() -> String {  
      
    let nowDate = Date()  
    let timeZone = TimeZone.init(identifier: "UTC")  
    let formatter = DateFormatter()  
    formatter.timeZone = timeZone  
    formatter.locale = Locale.init(identifier: "zh_CN")  
    formatter.dateFormat = "yyyy-MM-dd HH:mm"  
      
    let date = formatter.string(from: nowDate)  
    return date.components(separatedBy: " ").first!  
}  
2.传入一个Date类型的参数,返回一个日期字符串

    func dateConvertString(date:Date) -> String {
        
        let timeZone = TimeZone.init(identifier: "UTC")
        let formatter = DateFormatter()
        formatter.timeZone = timeZone
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        
        let date = formatter.string(from: date)
        return date.components(separatedBy: " ").first!
    }


 类似资料: