转换日期和时间格式均为“ 19-07-2018 08:10:24”的字符串,这两种字符串格式都不同

时间:2018-07-20 11:18:48

标签: ios iphone swift date format

我想以日期时间格式转换格式为“ 19-07-2018 08:10:24”的字符串。如果日期是今天,那么应该是“ 02:12 am”。如果日期是昨天,则应为“昨天”。否则,它应为“ DD / MM / yy”格式。目前,我在字符串formate中使用了时间和日期。

我想要字符串类型的最终答案。如果答案是“ DD / MM / YY”,则它应该为字符串格式。

2 个答案:

答案 0 :(得分:1)

使用日历日期功能:

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 ...
}

您可以在此处了解有关日历功能的更多信息:https://developer.apple.com/documentation/foundation/calendar

祝你好运!

答案 1 :(得分:1)

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)
    }