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
}
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...
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).
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.
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)
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
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With