如何使用Swift中使用DateFormatter返回日期?
我有一个小问题,我不知道该如何解决。我有一个与datepicker一起使用的日期。
我如何在代码中使用该格式的约会?
var minMaxRange : ClosedRange<Date> {
return dateStart...dateEnd
}
我希望datepicker从当前日期开始,而日期登录来自后端。 dateend是一个字符串,所以我对此没有问题。
var dateStart : Date {
let isoDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = .current
return dateFormatter.date(from: isoDate)
}
var dateEnd : Date {
let isoDate = syncViewModel.schedule[0].end
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = .current
return dateFormatter.date(from: isoDate) ?? Date.now
}
I have a little problem and I don't know how can I solve it. I have a closedRange of dates which i'm using with a DatePicker.
How can I have a date with that format that I have in the code bellow ?
var minMaxRange : ClosedRange<Date> {
return dateStart...dateEnd
}
I want the datePicker to start from the current date, and dateEnd is coming from the backend. dateEnd is a string so I do not have problem with this.
var dateStart : Date {
let isoDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = .current
return dateFormatter.date(from: isoDate)
}
var dateEnd : Date {
let isoDate = syncViewModel.schedule[0].end
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = .current
return dateFormatter.date(from: isoDate) ?? Date.now
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经有了一个
Date
...只需编写var dateStart = Date()
。然后,当您在屏幕上显示日期(开始和结束)时,您可以使用以下方法将它们格式化为字符串:
dateFormatter.string(from: dateStart)
You already have a
Date
... just writevar dateStart = Date()
.Then, you can format both dates (start and end) to a string when you show them on the screen, using:
dateFormatter.string(from: dateStart)