Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the date format of string if it's according to required format or not

I have the same question asked here in Java, is it possible in swift?

func stringToDate(str: String) -> Date{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    //check validation of str 

    return date
}
like image 527
Marry G Avatar asked Mar 07 '17 09:03

Marry G


People also ask

How to check if string is date format in Python?

python check if string is date format Code Example >>> import datetime >>> def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') ex...

How to check whether the date passed to query is date?

Checking whether the date passed to query is the date of the given format or not: SQL has IsDate () function which is used to check the passed value is date or not of specified format, it returns 1 (true) when the specified value is date otherwise it return 0 (false).

What is the use of strptime in date format?

Explanation : Formats match with date. Explanation : Month cannot be 14. In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity.

Is there a way to validate a date with regex?

But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case. Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)


2 Answers

Just same like Java, check if it can parse properly

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"

if dateFormatterGet.date(from: someDate) != nil {
    // valid format
} else {
    // invalid format
}
like image 173
Đào Minh Hạt Avatar answered Sep 30 '22 11:09

Đào Minh Hạt


For Swift 4 the syntax have changed a bit:

 func isValidDate(dateString: String) -> Bool {
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
    if let _ = dateFormatterGet.date(from: dateString) {
        //date parsing succeeded, if you need to do additional logic, replace _ with some variable name i.e date
        return true
    } else {
        // Invalid date
        return false
    }
}
like image 24
Ollikas Avatar answered Sep 30 '22 13:09

Ollikas