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)
Check if a string is a date or not
Here is a simple function that uses Date.parse() internally; when you pass a string with whitespaces to Date.parse()
, it will ignore non-digit chars and will return positive; hence you need to remove the space characters before passing it to Date.parse()
const a= 'Check 134';const b= '2020-01-15T10:47:54Z';const c= '1234';const tricky = '1'; // a number from -12 to 13 is valid
function isValidDate (str) { // optional condition to eliminate the tricky ones // since chrome will prepend zeros (000...) to the string and then parse it let noSpace = str.replace(/\s/g, '') if( noSpace.length < 3) { return false } return Date.parse(noSpace) > 0}
console.log(a,isValidDate(a))console.log(b,isValidDate(b))console.log(c,isValidDate(c))console.log(tricky,isValidDate(tricky))
// only in chromeconsole.log("'1' is ", Date.parse('1') > 1 ," since it can be ", new Date('1').toString())
How to check if a string is date?
Other person are also correct
This is your answer
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class date {
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isValidDate("20-01-2014"));
System.out.println(isValidDate("11-04-2015 22:01:33:023"));
System.out.println(isValidDate("32476347656435"));
}
}
Function to check if a string is a date
If that's your whole string, then just try parsing it:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== false) {
// it's a date
}
Correctly determine if date string is a valid date in that format
You can use DateTime::createFromFormat()
for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Demo!
Check if string is date or not in JavaScript
Got the solution
Instead of checking if it is date or not, I need to check first if it is number or not. If it is not number then only it can be a date.
Here is What I did and it worked.
var obj={ key1:"2015-10-10T11:15:30+0530", key2:2015, key3:"Normal String"}
function parseDate(dateStr){ if(isNaN(dateStr)){ //Checked for numeric var dt=new Date(dateStr); if(isNaN(dt.getTime())){ //Checked for date return dateStr; //Return string if not date. }else{ return dt; //Return date **Can do further operations here. } } else{ return dateStr; //Return string as it is number }}
console.log("key1 ",parseDate(obj.key1))console.log("key2 ",parseDate(obj.key2))console.log("key3 ",parseDate(obj.key3))
How to check if a string is a date value / date string in react
Why don't you try parsing the string into date? so something like new Date(dateString)
that will either spit out a date object or a string saying date is invalid. In your case you should try this const isDateValid = (date = "") => { let parsedDate = new Date(date); return parsedDate.toString() !== "Invalid Date"; }
That should do the trick.
How to validate if a string is a valid date in js
If Date.parse()
is not enough for you - but it may be enough - see the documentation at:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
then you may try:
- Moment.js
It is a library to parse, validate, manipulate, and display dates in JavaScript, that has a much richer API than the standard JavaScript date handling functions.
See also this answer for more libraries and links to tutorials.
Check if string has date, any format
The parse
function in dateutils.parser
is capable of parsing many date string formats to a datetime
object.
If you simply want to know whether a particular string could represent or contain a valid date, you could try the following simple function:
from dateutil.parser import parse
def is_date(string, fuzzy=False):
"""
Return whether the string can be interpreted as a date.
:param string: str, string to check for date
:param fuzzy: bool, ignore unknown tokens in string if True
"""
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False
Then you have:
>>> is_date("1990-12-1")
True
>>> is_date("2005/3")
True
>>> is_date("Jan 19, 1990")
True
>>> is_date("today is 2019-03-27")
False
>>> is_date("today is 2019-03-27", fuzzy=True)
True
>>> is_date("Monday at 12:01am")
True
>>> is_date("xyz_not_a_date")
False
>>> is_date("yesterday")
False
Custom parsingparse
might recognise some strings as dates which you don't want to treat as dates. For example:
Parsing
"12"
and"1999"
will return a datetime object representing the current date with the day and year substituted for the number in the string"23, 4"
and"23 4"
will be parsed asdatetime.datetime(2023, 4, 16, 0, 0)
."Friday"
will return the date of the nearest Friday in the future.- Similarly
"August"
corresponds to the current date with the month changed to August.
Also parse
is not locale aware, so does not recognise months or days of the week in languages other than English.
Both of these issues can be addressed to some extent by using a custom parserinfo
class, which defines how month and day names are recognised:
from dateutil.parser import parserinfo
class CustomParserInfo(parserinfo):
# three months in Spanish for illustration
MONTHS = [("Enero", "Enero"), ("Feb", "Febrero"), ("Marzo", "Marzo")]
An instance of this class can then be used with parse
:
>>> parse("Enero 1990")
# ValueError: Unknown string format
>>> parse("Enero 1990", parserinfo=CustomParserInfo())
datetime.datetime(1990, 1, 27, 0, 0)
Related Topics
Stylesheet Not Loading Because Mime Type Is Text/Html
Changing the Browser Zoom Level
How Add a New Key/Value Pair to a Json Object
Browserify :- Uncaught Typeerror: Fs.Readfilesync Is Not a Function
How to Unit Test If an Element Is Visible When the *Ngif Directive Is Used Using Jasmine in Angular
Force Download a Pdf Link Using Javascript/Ajax/Jquery
How to Disable Dates Before Today in Jquery Datepicker
Easiest Way to Open a Download Window Without Navigating Away from the Page
Websocket Connection Failed: Error During Websocket Handshake: Unexpected Response Code: 400
How to Download a Base64-Encoded Image
How to Apply Count Up Function to Multiple Values on the Page
Check If a String Is a Date Value
Generate Pdf from HTML in Div Using JavaScript
Import Image from Json Source (Create-React-App)
How to Change the Width of Angular Material Button
Node.Js Call Function If Button Clicked
Regular Expression to Accept Only Positive Numbers and Decimals