edo oktarifa
edo oktarifa

Reputation: 63

how to change date format in swift?

i got response json and show the date in label, i should change format date. i used swifty json and alamofire, this my code already i made:

func fetchDataHome() {

    DispatchQueue.main.async{
        let url = ""
        Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default).responseJSON { (response) in
            switch response.result{
            case .success(let value):
                print(value)

                let json = JSON(value)
                let kuota1 = json["data"]["kuota1"]["jumlah"].stringValue
                let kuota2 = json["data"]["kuota2"]["jumlah"].stringValue
                let kuota3 = json["data"]["kuota3"]["jumlah"].stringValue

                let kuota1Data = json["data"]["kuota1"]["tanggal"].stringValue
                let kuota2Data = json["data"]["kuota2"]["tanggal"].stringValue
                let kuota3Data = json["data"]["kuota3"]["tanggal"].stringValue

                let kuotaHariIni = modelKuota.init(jumlah: kuota1 , tanggal: kuota1Data)
                let kuotaBesok = modelKuota.init(jumlah: kuota2, tanggal: kuota2Data)
                let kuotaLusa = modelKuota.init(jumlah: kuota3, tanggal: kuota3Data)

                UserDefaults.standard.set(kuota1, forKey: "jumlah")
                UserDefaults.standard.set(kuota1Data, forKey: "tanggal")

                self.data.append(kuotaHariIni)
                self.data.append(kuotaBesok)
                self.data.append(kuotaLusa)

                self.collectionView.reloadData()


            case .failure(let error):
                print(error)
            }
        }
    }
}

this for data in cell collection view cell:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BerandaCollectionViewCell", for: indexPath) as! BerandaCollectionViewCell
    let dataKuota = data[indexPath.row]

    cell.jumlah.text = dataKuota.jumlah

    cell.tanggal.text = dataKuota.tanggal


    return cell
}

this response i get from json:

  28022019 (dd/MM/YYYY)

my expectations:

 28 February 2019

Upvotes: 0

Views: 320

Answers (1)

staticVoidMan
staticVoidMan

Reputation: 20234

Use DateFormatter with appropriate formats in order to convert a String to Date and back to String

func processDate(string: String, fromFormat: String = "ddMMyyyy", toFormat: String = "dd MMMM yyyy") -> String? {
    let formatter = DateFormatter()

    formatter.dateFormat = fromFormat
    guard let date = formatter.date(from: string) else { return nil }

    formatter.dateFormat = toFormat
    return formatter.string(from: date)
}

//using defaults formats of "ddMMyyyy" to "dd MM YYYY"
let s1 = processDate(string: "28022019") //28 February 2019

//using specific formats to match your input string
let s2 = processDate(string: "28-02-2019", fromFormat: "dd-MM-yyyy", toFormat: "dd MMMM yyyy") //28 February 2019

//invalid case, string and initial format don't match
let s3 = processDate(string: "28022019", fromFormat: "MM", toFormat: "MMMM") //nil

Date Formats CheatSheet: http://nsdateformatter.com/

Upvotes: 1

Related Questions