简体   繁体   中英

How to compare two different date formats in swift

对于相同的对象,我从API中有两种不同的日期格式,一种是“ yyyy-MM-dd”,另一种是“ dd-MM-YYYY”。如何区分该对象包含特定格式。

Use this may be worked for you.

 let formatter = DateFormatter()
 formatter.dateFormat = "yyyy-MM-dd" // YOUR DATE FORMATE

 if let date = formatter.date(from: dateString) {
       // IT CONTAIN YOUR DATE FORMATE
 }

Try this,

let datestring = "2019-06-13" // try 13-06-2019 as well

let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"
var date = dateformatter.date(from: datestring)

if date == nil {
   dateformatter.dateFormat = "dd-MM-yyyy"
   date = dateformatter.date(from: datestring)
 }
 print(date!)

there should be many other ways to this and hope this will help to you.

You don't need to worry about whatever the format is, You just need to populate it into Date Object by using date formatter. After that you can use that Date Object where ever you want to use. Like

let datestring = "2019-06-13"

let dateformatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
var date1 = formatter.date(from: dateString)

and for other type of date

let dateString = "13-06-2019"

let dateformatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
var date2 = formatter.date(from: dateString)

Now you got 2 date objects date1 & date2 , use these in your code without bothering about their previous formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM