如何将 String 转换为 Date,在 Swift 中只获取日期而不获取时间?
How to convert String to Date getting only date and not time in Swift?
我目前正在从 API 中获取日期,格式为:
"2018-06-09T09:20:48"
我想将这个日期与今天、明天进行比较,否则我有另一个条件。
我所做的是这样的:
func dateFormatter(date: String){
let today = Date() //2018-06-06 04:54:46 +0000
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today) //2018-06-07 04:54:46 +0000
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date_db = dateFormatter.date(from: date) //2018-06-06 12:32:02 +0000
if today == date_db{
print("It is today")
}
else if tomorrow = date_db {
print("It is tomorrow")
}
else {
"After Some Days"
}
}
这不起作用,因为它正在比较 dateTime 和 dateTime,这就是为什么,但我只想要今天、明天和 date_db 的日期,以便我可以比较它们。我该怎么做?
几个问题。首先,您的日期格式完全错误。你有错误的时区。你有错误的语言环境。修复这些问题后,您可以解析日期字符串。
然后确定日期是今天还是明天(忽略时间)的正确方法是使用 Calendar
方法 isDateInToday
和 isDateInTomorrow
.
这是你的代码,所有内容都已修复:
func dateFormatter(date: String){
let dateFormatter = DateFormatter()
// For a string like "2018-06-09T09:20:48"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // assume date is GMT+0
if let date_db = dateFormatter.date(from: date) {
if Calendar.current.isDateInToday(date_db) {
print("It is today")
} else if Calendar.current.isDateInTomorrow(date_db) {
print("It is tomorrow")
} else {
print("After Some Days")
}
} else {
print("Unexpected date string")
}
}
我目前正在从 API 中获取日期,格式为:
"2018-06-09T09:20:48"
我想将这个日期与今天、明天进行比较,否则我有另一个条件。
我所做的是这样的:
func dateFormatter(date: String){
let today = Date() //2018-06-06 04:54:46 +0000
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today) //2018-06-07 04:54:46 +0000
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date_db = dateFormatter.date(from: date) //2018-06-06 12:32:02 +0000
if today == date_db{
print("It is today")
}
else if tomorrow = date_db {
print("It is tomorrow")
}
else {
"After Some Days"
}
}
这不起作用,因为它正在比较 dateTime 和 dateTime,这就是为什么,但我只想要今天、明天和 date_db 的日期,以便我可以比较它们。我该怎么做?
几个问题。首先,您的日期格式完全错误。你有错误的时区。你有错误的语言环境。修复这些问题后,您可以解析日期字符串。
然后确定日期是今天还是明天(忽略时间)的正确方法是使用 Calendar
方法 isDateInToday
和 isDateInTomorrow
.
这是你的代码,所有内容都已修复:
func dateFormatter(date: String){
let dateFormatter = DateFormatter()
// For a string like "2018-06-09T09:20:48"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // assume date is GMT+0
if let date_db = dateFormatter.date(from: date) {
if Calendar.current.isDateInToday(date_db) {
print("It is today")
} else if Calendar.current.isDateInTomorrow(date_db) {
print("It is tomorrow")
} else {
print("After Some Days")
}
} else {
print("Unexpected date string")
}
}