This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Compare two dates with JavaScript
(43 answers)
Comparing date part only without comparing time in JavaScript
(28 answers)
Closed last year.
I would like to know how to compare any two different date strings in javascript.
Two Date Strings, d1 and d2 are always in the format , dd mmm yyyy and yyyy-mm-dd
How to compare datestring whether is same or not in javascript
Below datestring is example,
var d1 = "12 Feb 1990"
var d2 = "1990-02-12"
if(d1.split(' ').[1] === new Date().toLocaleString('en-US', {month: 'short'})){
return true;
}
else {
return false
}
If you want to compare only the date string then the .toDateString method is all you need. Something like
You can read more about the toDateString method on MDN
let d1 = "12 Feb 1990"
let d2 = "1990-02-12"
const d1String = new Date(d1).toDateString()
const d2String = new Date(d2).toDateString()
if (d1String === d2String) {
console.log('Equal');
} else {
console.log('Not equal');
}
Here's some code that reorders the "1990-02-12" string and compares it to the "12 Feb 1990" one:
function d2ToNormalDate(string) {
return string.split("-")[1] + "-" + string.split("-")[2] + "-" + string.split("-")[0];
}
function areDateStringsEqual(string1, string2) {
// Expects string1 to be a string like "12 Feb 1990" and
// expects string2 to be a string like "1990-02-12".
// returns a boolean.
return new Date(d2ToNormalDate(string2)).toString() === new Date(string1).toString()
}
Related
This question already has answers here:
What are valid Date Time Strings in JavaScript?
(2 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 7 months ago.
I was trying to check if a string is valid date string or not with below code
const isValidDate = (date: any) => {
return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
For example :
let dateStr = "some-random-string-09"
console.log(isValidDate(dateStr)) // returns true instead of false
But if I remove the 09 from the string or add some text at the end of the string it returns the expected result.
for Ex:
let dateStr = "some-random-string"
console.log(isValidDate(dateStr)) // returns false as expected
it is really strange behaviour. Is there a way to validate this particular type of string in TypeScript?
You can achieve things like below code:
const incorrectDate = Date.parse('01 Jan 1970 00:00:00 GMT 09');
const CorrectDate = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(incorrectDate );
// expected output: NaN
console.log(CorrectDate );
// expected output: 818035920000
So if output is NaN then you can write your business logic
This question already has answers here:
What are valid Date Time Strings in JavaScript?
(2 answers)
Closed 1 year ago.
I have two dates .
var dateOne = "24/04/1995"
var dateTwo = "24/04/1998"
How can i check if one date is bigger than the other?
I tried this :
function myFunction() {
var d1 = Date.parse(dateOne);
var d2 = Date.parse(dateTwo);
if (d1 < d2) {
alert ("Error! Date did not Match");
}
}
but its not working =(
there is a method for this dd/mm/yyyy format?
Relying on the docs around Date
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
You can simply cast to a Number and compare:
const isDateOneBigger = +dateOne > +dateTwo;
However in your case your Dates are invalid. You can check this by logging out d1 which will result in NaN. If you take a look at How to convert dd/mm/yyyy string into JavaScript Date object? you'll see how you can convert your strings into correct dates.
use the getTime() as so
function myFunction() {
var d1 = new Date(dateOne);
var d2 = new Date(dateTwo);
if (d1.getTime() < d2.getTime()) {
alert ("Error! Date did not Match");
}
}
the getTime() method convert the date into milliseconds
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
How to get 2 digit year w/ Javascript? [duplicate]
(5 answers)
Closed 3 years ago.
I have string in the following format "30.11.2019". I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19".
The following code doesn't work
var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear();
new Date() does not work with a single string argument in that format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Easiest way is to call it with 3 arguments (year, month, day).
Do note that month is the month index (0 based), so November (11th month) is actually 10th in the format that Date expects.
new Date(2019, 10, 30).getFullYear() % 100;
// returns 19;
If you can't do it this way and you simply must work around the string format mentioned, then you can just do
const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);
I'm not entirely sure if you want only short representation of the year or whole date, BUT with short representation of the year on it - if so, then I would suggest using toLocaleDateString method:
new Date(2019, 10, 30).toLocaleDateString('pl', {day: 'numeric', month: 'numeric', year: '2-digit'})
It will return you:
"30.11.19"
or if you want to get the short year date only:
new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})
it will return you:
"19"
You can get last two digits with the following code:
var strDate = new Date(); // By default Date empty constructor give you Date.now
var shortYear = strDate.getFullYear();
// Add this line
var twoDigitYear = shortYear.toString().substr(-2);
Since the string you're using isn't in a format recognized by Date.parse() (more on that here), you need to manually create that Date object.
For example:
const strDate = '30.11.2019';
let [d,m,y] = strDate.split(/\D/);
const date = new Date(y, --m, d);
console.log(date.getFullYear())
You can then use Date.getFullYear() to get the year and extract the last two digits, as you need.
do not need split string, I think.
using moment
yarn add moment
const moment = require( 'moment' );
const simpleYear = moment( "30.11.2019", "DD.MM.YYYY" ).format( "YY" );
console.log( "simpleYear = " + simpleYear );
var strDate = "30.11.2019";
var lastdigit = strDate.slice(-2);
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);
I use Date() function to convert string to date object . The problem is , If i give Date("April , 31 ,2012") it will take it as May , 01 , 2012 (for the rest of the days its working) Please check my approach is correct from the code below.
function TestDate(objValue,strError){
var ret=true;
var frmdate=objValue.value;
var datesplit=frmdate.split("-");
var y =datesplit[0];
var m=datesplit[1];
var d=datesplit[2];
var testdate;
// Create date object using given input data
testdate = new Date(m+"/"+d+"/"+y);
alert("Created date"+testdate.toString());
var td=testdate.getDate();
var tm=testdate.getMonth()+1;
var ty =testdate.getFullYear();
alert(d+"="+td);
alert(m+"="+tm);
alert(y+"="+ty);
var valid=((d==td) && (m==tm) && (y==ty));
alert(valid);
if(valid == false)
{
ret =false;
}
return ret;
}
As sayed by #ajreal in comments, April has only 30 days.
The internal date object increments the month to have a valid date.
The code:
testdate = new Date(m+"/"+d+"/"+y);
is depends on non-standard, implementation specific parsing of the string. Far better to use the data you started with to create a date unambiguously:
testdate = new Date(y, m - 1, d);
As for validating a date, a simple function using an ISO8601 compliant date of format yyyy-mm-dd is:
function validateDate(dateString) {
var bits = dateString.split('-');
var date = new Date(bits[0], bits[1] - 1, bits[2]);
return date && date.getFullYear() == bits[0] && date.getDate() == bits[2];
}
That way if the string passed to the function is turned into a date, you can check that the date so created matches the input. If not, it wasn't valid and the function returns false. It also returns false if the string doesn't get turned into a date.