[英]Swift: Format a a start and end date into a single string
I have these two dates in string format: 我有两个日期以字符串格式:
let startDate = "2018-06-14"
let endDate = "2018-06-17"
I would like to format them together as such: 我想将它们格式化为:
June 14-17, 2018
2018年6月14-17日
However, if the start and end date fall on different months it should be formatted like this: 但是,如果开始日期和结束日期位于不同的月份,则应采用以下格式:
June 29 - July 1, 2018
2018年6月29日至7月1日
And if the start and end date fall on different years it should be formatted like this: 如果开始日期和结束日期位于不同的年份,则应采用以下格式:
December 29, 2018 - January 1, 2019
2018年12月29日-2019年1月1日
Is there an easy way of doing this using Swift's native DateFormatter
? 有使用Swift的本机
DateFormatter
做到这一点的简单方法吗?
Is there a popular pod that can help with this? 是否有受欢迎的吊舱可以帮助您解决此问题?
What's the best practice to accomplish this formatting? 完成此格式化的最佳实践是什么?
Here's my answer: 这是我的答案:
if let startDate = startDateString.toDate(withFormat: "yyyy-MM-dd"),
let endDate = endDateString.toDate(withFormat: "yyyy-MM-dd") {
let formatter = DateIntervalFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none
dateLabel.text = formatter.string(from: startDate, to: endDate)
}
And this extension: 和这个扩展名:
extension String {
func toDate(withFormat format: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: self)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.