Convert string of format “19-07-2018 08:10:24” in date and time both different string format

梦想的初衷 提交于 2021-01-29 06:13:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!