How to Validate a Date

Check if date is a valid one

Was able to find the solution.
Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

How to validate a date?

One simple way to validate a date string is to convert to a date object and test that, e.g.

// Expect input as d/m/y

function isValidDate(s) {

var bits = s.split('/');

var d = new Date(bits[2], bits[1] - 1, bits[0]);

return d && (d.getMonth() + 1) == bits[1];

}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {

console.log(s + ' : ' + isValidDate(s))

})

Detecting an invalid date Date instance in JavaScript

Here's how I would do it:

if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}

Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:

function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}

Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32) and "invalid date objects" (new Date('foo')). This answer does not deal with validating date input, only if a Date instance is valid.

Check if a string is a date value

Would Date.parse() suffice?

See its relative MDN Documentation page.

Date.parse returns a timestamp if string date is valid. Here are some use cases:

// /!\ from now (2021) date interpretation changes a lot depending on the browser
Date.parse('01 Jan 1901 00:00:00 GMT') // -2177452800000
Date.parse('01/01/2012') // 1325372400000
Date.parse('153') // NaN (firefox) -57338928561000 (chrome)
Date.parse('string') // NaN
Date.parse(1) // NaN (firefox) 978303600000 (chrome)
Date.parse(1000) // -30610224000000 from 1000 it seems to be treated as year
Date.parse(1000, 12, 12) // -30610224000000 but days and month are not taken in account like in new Date(year, month,day...)
Date.parse(new Date(1970, 1, 0)) // 2588400000
// update with edge cases from comments
Date.parse('4.3') // NaN (firefox) 986248800000 (chrome)
Date.parse('2013-02-31') // NaN (firefox) 1362268800000 (chrome)
Date.parse("My Name 8") // NaN (firefox) 996616800000 (chrome)

How do I validate a date string format in python?

>>> import datetime
>>> def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
validate('2003-12-32')
File "<pyshell#18>", line 5, in validate
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD

how to validate a date in python

Rather than use time.strptime(), use datetime.datetime.strptime() and then validate the resulting object to be within your range:

from datetime import datetime, date
date_input = input('Date (mm/dd/yyyy): ')
try:
valid_date = datetime.strptime(date_input, '%m/%d/%Y').date()
if not (date(2014, 1, 1) <= valid_date <= date(2014, 8, 7)):
raise ValueError('Date out of range')
except ValueError:
print('Invalid date!')

If no exception is thrown, valid_date is bound to a datetime.date() instance.

How to validate the date format of a column in Pyspark?

You can filter out the rows after converting to date type.

Example:

df.show()
#+----------+----+
#| Date|name|
#+----------+----+
#|12/12/2020| a|
#|24/01/2019| b|
#|12/24/2020| d|
#| nan| e|
#+----------+----+

from pyspark.sql.functions import *

df.withColumn("output",to_date(col('Date'),'dd/MM/yyyy')).\
filter(col("output").isNotNull()).\
show()
#+----------+----+----------+
#| Date|name| output|
#+----------+----+----------+
#|12/12/2020| a|2020-12-12|
#|24/01/2019| b|2019-01-24|
#+----------+----+----------+

#without adding new column
df.filter(to_date(col('Date'),'dd/MM/yyyy').isNotNull()).show()
#+----------+----+
#| Date|name|
#+----------+----+
#|12/12/2020| a|
#|24/01/2019| b|
#+----------+----+

Validate date using Joi without convert it to utc format

A possible workaround is to initiate a new date object from the date the user has sent, and next, you can get the full year, month, and day... also if you use this way, you will get the date in this format no matter what browser the user is using.

const Joi = require('joi').extend(require('@joi/date'));
...
const schema = Joi.object({
f_title: Joi.string().required(),
dateVarFromUser: Joi.date().format('YYYY-MM-DD').required(),
});
###
// Rest of your code
###

Before sending the request to the DB, add the following

const datObj = new Date(dateVarFromUser);
dateVarFromUser = datObj.getFullYear() + '-' + (datObj.getMonth()+1) + '-' + datObj.getDate()

###
// Then, you could send it to the SQL handler/function
###



Related Topics



Leave a reply



Submit