问题
I want to Convert string of format "19-07-2018 08:10:24" in date time format. If the date is today then it should be "02:12 am". If the date is of yesterday then it should be like "Yesterday". Otherwise it should be in "DD/MM/yy" format. Currently I am having the time and date in string formate.
I want the final answer in string type. If the answer is "DD/MM/YY", then it should be in string format.
回答1:
Use the Calendar date functions:
func format(date: Date) -> String {
let calendar = Calendar.current
if calendar.isDateInToday(date) {
// process your "Today" format
return ...
}
if calendar.isDateInYesterday(date) {
// process your "Yesterday" format
return ...
}
if calendar.isDateInTomorrow(date) {
// process your "Tomorrow" format
return ...
}
// process your "full date/time format"
return ...
}
You can read more about the Calendar functions here: https://developer.apple.com/documentation/foundation/calendar
回答2:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"//19-07-2018 08:10:24
let date = dateFormatter.date(from: "15-07-2018 08:10:24")
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDate = dateFormatter.string(from: date!)
let dateToday = (Calendar.current as NSCalendar).date(byAdding: .day, value: 0, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateToday = dateFormatter.string(from: dateToday1)
let dateYesterday = (Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateYesterday = dateFormatter.string(from: dateYesterday1)
if(startDate == strdateToday)
{
dateFormatter.dateFormat = "HH:mm"
let startDate = dateFormatter.string(from: date!)
print(startDate)
}
else if(startDate == strdateYesterday)
{
print("Yesterday")
}
else
{
print(startDate)
}
来源:https://stackoverflow.com/questions/51441372/convert-string-of-format-19-07-2018-081024-in-date-and-time-both-different-s