This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 4 years ago.
I tried to compare two date objects in angular 4 but it always returning false
below are my code snippet
CheckForHoliday(d: Date) {
let simpleDate = new Date(d.getFullYear(), d.getMonth(), d.getDay());
let hDate = new Date(2018, 9, 1);
console.log(simpleDate + "==========" + hDate);
console.log(hDate === simpleDate);
return (hDate === simpleDate);
}
The output is as below
Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)==========Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)
false
Any Idea why it returning false when the printed values look same?
You could do a date.getTime() and then compare the two numbers
You should compare the dates in the date Objects. If you call the getDate() method on the date Objects you will get true.
hDate.getDate() === simpleDate.getDate() //=> returns true
new Date will return an object and you cannot compare objects like that. Try converting both of them to string before comparing them.
Do it like this
CheckForHoliday(d: Date) {
let simpleDate = new Date(d.getFullYear(), d.getMonth(), d.getDay());
let hDate = new Date(2018, 9, 1);
console.log(simpleDate + "==========" + hDate);
console.log(hDate === simpleDate);
return (hDate.toString() === simpleDate.toString());
}
Related
This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I have Datetimes formated as "16 Apr 2020 02:07 PM CST" and I need to compare it to another datetime just like that to know which date came first.
What I tried to do until now was:
var firstDate = "16 Apr 2020 02:07 PM CST";
var secondDate = "23 Apr 2020 06:07 AM CST";
var diff = Math.abs(firstDate - secondDate);
That or I tried to check if one was greater than the other and got similar results.
You should check time in milliseconds (timestamp) to compare dates:
var firstDate = new Date("16 Apr 2020 02:07 PM CST");
var secondDate = new Date("23 Apr 2020 06:07 AM CST");
if (firstDate.getTime() < secondDate.getTime()) {
console.log('First Date came first');
} else {
console.log('Second Date came first');
}
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I hardcoded date string in one variable and passing this in new Date()
let hardcoded = "10/4/2018 12:00:00 AM";
console.log($.type(hardcoded)); // String is printing
console.log(hardcoded); // 10/4/2018 12:00:00 AM is printing
var d = new Date(hardcoded);
console.log(d); // Thu Oct 04 2018 00:00:00 GMT+0530 (India Standard Time) is printing
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here in variable 'd' i am getting proper date .. no any issue.
But in below case same string i am getting in convertedDate variable what i hardcode above but its not working ..
let convertedDate = new Date().toLocaleString("en-us", {
timeZone: 'UTC'
});
console.log($.type(convertedDate)); // String is printing
console.log(convertedDate); // 6/26/2019 12:02:50 PM is printing
var d = new Date(convertedDate);
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
but here in variable d :- "Invalid date" is coming..
Try this
var d = new Date(convertedDate.toDateString())
Your passing
6/26/2019, 12:30:57 PM
but Date() is expecting
2019-06-26T11:30:57.000Z
.toDateString() will convert
6/26/2019, 12:30:57 PM
to
2019-06-26T11:30:57.000Z
As you are having this problem in IE11, I found this which may cast light on the issue
IE's toLocaleString has strange characters in results
When using the JavaScript Date instance to create new date, the date string given to the date constructor should be an RFC2822 or ISO 8601 formatted date, not local.
So, I suggest you could modify your code as below:
let convertedDate = new Date();
var convertedDatestring = convertedDate.toLocaleString("en-us", {
timeZone: 'UTC'
});
console.log($.type(convertedDatestring)); // String is printing
console.log(convertedDatestring); // 6/26/2019 3:24:04 PM
var d = new Date(convertedDate.toUTCString());
console.log(d); //Wed Jun 26 2019 23:24:04 GMT+0800
I would like to compare the given date in the below format in JaveScript. I have tried the following,
Thu May 19 2016 00:00:00 GMT+0530 (India Standard Time)
Thu May 20 2016 00:00:00 GMT+0530 (India Standard Time)
var ExpiryDate = userAccount.ExpiryDate();
var datetoday = new Date();
var Expired = (DateTime.Compare(ExpiryDate, datetoday) == -1 ) ? true : false;
//if expiry date is less than today date then var expired should be true
But didn't worked. I could not compare those two dates. It results in un handled exception. Is there any other way to do this date comparison in JaveScript ?
I have referred the following answers in SO but they are in different date format. So that I have raised this question,
javascript compare two dates and throw an alert
Javascript comparing two dates has wrong result
Compare two dates in JavaScript
Javascript compare two dates to get a difference
Any suggestion would be helpful.
var date = new Date();
//# => Fri May 20 2016 16:09:43 GMT+0530 (India Standard Time)
var date2 = new Date();
date2.setDate(date.getDate() - 1);
//# => Thu May 19 2016 16:09:43 GMT+0530 (India Standard Time)
date > date2 //# => true
use getTime()
var date1 = (new Date("20 May 2016")).getTime();
var date2 = (new Date("19 May 2016")).getTime();
date1>date2
You will find some good method here
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
How can I turn this Fri Feb 21 2014 00:00:00 GMT-0800 (Pacific Standard Time) into just this 2014-02-21 using javascript ?
You can break the string into its parts, then format the bits into what you need:
// Reformat string like: Fri Feb 21 2014 00:00:00 GMT-0800 (Pacific Standard Time)
// do yyyy-mm-dd
function reformatDateString(s) {
function z(n){return (n<10?'0':'') + n;}
var months = {jan:'01', feb:'02', mar:'03', apr:'04', may:'05', jun:'06',
jul:'07', aug:'08', sep:'09', oct:'10', nov:'11', dec:'12'};
s = s.split(/[ :]/g);
return s[3] + '-' + months[s[1].toLowerCase()] + '-' + z(s[2]);
}
You can use the Date constructor, but it's not necessary here. Using the constructor to parse strings is problematic since the string in the OP doesn't fit the format specified in ES5 (which is not supported by all browsers in use) and parsing is otherwise implementation dependent.
So to use Date you need to parse the parts anyway, resulting in many extra function calls.
Using standard string/array manipulation
var timeStamp = 'Fri Feb 21 2014 00:00:00 GMT-0800 (Pacific Standard Time)',
months = {
Jan: 1,
Feb: 2,
Mar: 3,
Apr: 4,
May: 5,
Jun: 6,
Jul: 7,
Aug: 8,
Sep: 9,
Oct: 10,
Nov: 11,
Dec: 12
},
parts = timeStamp.split(' ', 4).slice(1),
myStamp;
function pad(val) {
if (val < 10) {
val = '0' + val;
}
return val;
}
parts[0] = months[parts[0]];
parts.unshift(parts.pop());
parts[1] = pad(parts[1]);
parts[2] = pad(parts[2]);
mystamp = parts.join('-');
console.log(mystamp);
Output
2014-02-21
On jsFiddle
The date Fri Feb 21 2014 00:00:00 GMT-0800 is in standard RFC 2822 format so you can create a new date using new Date() passing it as a parameter. This will convert it into UTC (milliseconds since 1/1/1970) which you can manipulate.
You can then convert UTC into ISO 8601 extended format (2014-02-21T00:00:00.000Z) with the toISOString() method and get the text before the T:
var utcDate = new Date('Fri Feb 21 2014 00:00:00 GMT-0800');
var isoExtendedDate = utcDate.toISOString();
var isoSimpleDate = isoExtendedDate.split("T")[0];
I'm unable to delete this since the OP chose it as the answer (OP please choose Xotic750's) answer.
See Xotic750's answer
In the following date conversion after converting back the long integer The date says october instead of september
var date = 2013-09-23 18:31
startdate = getTimeStamp(date); //1382533260000
Now
t=1382533260000
rt = new Date(t)
//Wed Oct 23 2013 18:31:00 GMT+0530 (India Standard Time)
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1],d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
In JavaScript, month numbers are numbered 0-11.
If you're parsing from components like this into the Date constructor you'll have to subtract one from the number:
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1] - 1,d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
Months are zero-based, so January is zero, February is one, etc..
So you need to use d1[1]-1 in your new Date() constructor.
Javascript month parameter starts from 0 upto 11 so, passing 8 means september