如何快速更改日期格式?

时间:2019-02-26 06:52:03

标签: swift

我收到响应json并在标签中显示日期,我应该更改格式日期。 我用了迅捷的json和alamofire, 这是我已经编写的代码:

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

此为单元格集合视图单元格中的数据:

    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
}

我从json获得此响应:

  28022019 (dd/MM/YYYY)

我的期望:

 28 February 2019

1 个答案:

答案 0 :(得分:1)

以适当的格式使用DateFormatter,以便将String转换为Date,然后再转换回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

日期格式备忘单:http://nsdateformatter.com/