Home > Mobile >  Date format in Swift ios
Date format in Swift ios

Time:09-05

how i can implement this date format 1st July,2021 17:00.My current code is

func changeFormat(_ toFormat: String,_ dateStr: Date?) -> String{
        let date = dateStr ?? Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = toFormat
        return dateFormatter.string(from: date)
    }
    
func covertStringToDate(_ date: String) -> Date {
        let isoDate = date

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.date(from:isoDate)!
        
    }

CodePudding user response:

If u want to convert any Date object to this format do this.

let date = Date()

//create the date format without the day
let dateFormatter = DateFormatter()
dateFormatter.locale     = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM,yyyy HH:mm"
let dateWithoutDay = dateFormatter.string(from: date)

//get the day from the date
let dayFormatter = DateFormatter()
dayFormatter.locale     = Locale(identifier: "en_US_POSIX")
dayFormatter.dateFormat = "d"
let day = dayFormatter.string(from: date)

//create a number formatter to get st/nd/rd/th suffix
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let dayWithSuffix = numberFormatter.string(from: NSNumber(value:Int(day)!))
print("\(dayWithSuffix!) \(dateWithoutDay)") // --> 3rd September,2022 22:52

If u want to convert this type of date (1st July,2021 17:00 ) to a Date object do this.

let dateString = "1st July,2021 17:00"
let dateSuffix = dateString.components(separatedBy: CharacterSet.decimalDigits).joined().prefix(2)
let dateFormatter = DateFormatter()
dateFormatter.locale     = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd'\(dateSuffix)' MMMM,yyyy HH:mm"
let date = dateFormatter.date(from: "1st July,2021 17:00")
print(date!) // ->> 2021-07-01 11:30:00  0000
  • Related