Swift5:Date->String思路:
1.实例化一个DateFormatter对象
2.根据项目需求修改这个对象的属性
3.用这个对象的string方法,放入想要转化的日期或时间(Date类型)
最基本的用法:
指定dateFormat属性
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒"
print(dateFormatter.string(from: Date())) //2019年05月10日 22时22分22秒
中级用法:
指定dateStyle或timeStyle属性+locale属性
let dateFormatter = DateFormatter()
//dateStyle和timeStyle默认都是none,两者至少有一个
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
//改成中文
dateFormatter.locale = Locale(identifier: "zh_CN")
print(dateFormatter.string(from: Date())) //2019年5月10日 下午10:22
dateStyle(medium和long对中文来说没区别):
.short // 2019/5/10
.medium // 2019年5月10日
.long // 2019年5月10日
.full // 2019年5月10日 星期五
timeStyle:
.short // 下午10:22
.medium // 下午10:22:22
.long // GMT+8 下午10:22:22
.full // 中国标准时间 下午10:22:22
一般来说都选.medium
就够用了
高级用法:
上述dateStyle和timeStyle无法满足项目需求的话,可以设定一个本地化模板。
这样以后所有用这个dateFormatter转化的date都会遵循这个模板的格式:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.setLocalizedDateFormatFromTemplate("H")
print(dateFormatter.string(from: Date())) // 22时
print(dateFormatter.string(from: Date(timeIntervalSinceReferenceDate: 410220000))) // 6时
关于yyyy-MM-dd等unicode的标准日期格式可以参考这里:
http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns
广告时间:小弟的iOS12零基础视频教程(每章皆可试听):
http://m.study.163.com/provider/480000001852411/index.htm?share=2&shareId=480000001852411
网友评论