Comparing datetime to the current date javascript [duplicate] - javascript

This question already has answers here:
How to know date is today?
(3 answers)
Closed 2 years ago.
I have an object that contains a property of date with a value of 2020-09-02T00:00:00.000Z. I want this value to be compared if it is within the current date or not, meaning if it is within 2020-09-01 00:00:00.00 to 2020-09-01 11:59:59.99. How will I be able to achieve this? This is my initial line of codes. Hope you can help me. Cheers!
for(let a = 0, c = arr3.length; a < c; a++){
let olddate = arr3[a].scheduled_time_start.valueOf();
}

You can compare native Date objects with comparison (<, <=, >, >=) operators.
const isDateInbetween = (date, startDate, endDate) =>
date > startDate && date < endDate;
const pastDate = new Date('2020-09-01T00:00:00.000Z');
const futureDate = new Date('2020-09-01T11:59:59.999Z');
const currDate = new Date('2020-09-02T00:00:00.000Z');
console.log(isDateInbetween(currDate, pastDate, futureDate)); // false

Related

How to compare month and year in JavaScript? [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 7 months ago.
i need to compare date.like input date is greater than current next month.using normal date in JavaScript.
//comparison_date is date which is current date + one month
// 14/07/2022 + One Month
input_date : 14/07/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// false
}
input_date : 14/08/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// false
}
input_date : 14/09/2022
comparison_date : 14/08/2022
if(input_date> comparison_date){
// true
}
input_date : 22/12/2022
comparison_date : 14/01/2023
if(input_date> comparison_date){
// false
}
you can do something like this
const toDate = dateString => {
const [day, month, year] = dateString.split('/')
return new Date(`${year}-${month}-01 00:00:00`)
}
console.log(toDate('14/07/2022') > toDate('14/08/2022'))
console.log(toDate('14/08/2022') > toDate('14/08/2022'))
console.log(toDate('14/09/2022') > toDate('14/08/2022'))
console.log(toDate('22/12/2022') > toDate('14/01/2023'))
if you just need to compare year and month you can also do something more simple like this
const toYearMonth = stringDate => {
const [_, month, year] = stringDate.split('/')
return Number(`${year}${month}`)
}
console.log(toYearMonth('14/07/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('14/08/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('14/09/2022') > toYearMonth('14/08/2022'))
console.log(toYearMonth('22/12/2022') > toYearMonth('14/01/2023'))
Text doesn't compare datewise, you need to convert to a timestamp and compare the values, the Date class would do this for you
const date1 = new Date("2022-07-14");
const date2 = new Date("2022-08-14");
console.log(date1.getTime() > date2.getTime());
console.log(date1.getTime() => date2.getTime());
console.log(date1.getTime() < date2.getTime());
console.log(date1.getTime() >= date2.getTime());
console.log(date1.getTime() == date2.getTime());
assuming you want the current date + one month you can do
current = new Date();
nextMonth = current.setMonth(current.getMonth()+1);//note this changes the value of "current"
however depending on the type of compare you want you may need to customise the compare, ie date one is midnight case 2 is midnight and a microsecond is this greater than or equal? depends on your situation
note: you appear to be using the en-GB date format which is a pain try to use ISO yyyy-mm-dd, it simplifies many things

Check if date is bigger then other date (dd/mm/yyyy) [duplicate]

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

Dates changing when I change another date [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Changing date copied from an object [duplicate]
(3 answers)
Closed 2 years ago.
so I 'm having a strange bug here related to changing the month of a date object. here is the code.
let date = new Date();
let captions = [];
for (let i=0; i < 12; i++) {
let newDate = date;
newDate.setMonth(date.getMonth() - i);
let month = newDate.toLocaleString('default', { month: 'short' });
let year = newDate.getFullYear();
captions.push({month, year});
}
The thing is value of date variable is changing every loop. I can understand why.
Anyone?
Your issue is with this assignment: let newDate = date;
What happens is that now newDate is a reference to your original date variable.
As Lennholm suggested in his comment below:
"it's not a reference to the original variable but to the same object
(in memory) that the original variable also references. The two
variables are independent of each other."
To avoid that change it to this: let newDate = new Date(date);
Check this stackblitz.

How do I convert strings into dates in Javascript? [duplicate]

This question already has answers here:
Parse date without timezone javascript
(16 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I have a list of string dates that I retrieve from a website.
const appDate = await page.evaluate(() => {
const dates = Array.from(document.querySelectorAll('li.det-comment-list-every div.comment-date'))
return dates.map(font => font.textContent)
});
I tried to convert them into Date objects in a for loop.
Example of appDate array :
['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30
04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01',
'2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
let nDates = [];
for(let date of appDate){
var d = new Date(date);
nDates.push(d);
}
console.log(nDates);
However, the console gives me "invalid date".
[ Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date,
Invalid Date ]
How can I get my dates to convert into date format?
You might have confused that for..of with for..in, vice versa. You have to be careful with iterating arrays using for..in, it iterates through enumerable properties of an object as well. Try doing this instead:
const dates = ['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30 04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01', '2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
const nDates = [];
for(let date of dates){
const d = new Date(date);
nDates.push(d);
}
console.log(nDates);
If you insist on using a for..in loop, you will need to iterate via its key-value pairs:
const nDates = [];
for(let index in dates){
const d = new Date(dates[index]);
nDates.push(d);
}
console.log(nDates);
Or better still, a shorter, one-liner approach:
const nDates = dates.map(date => new Date(date));
console.log(nDates);
This is a case of wrong use of for..in.. loop. If you try to log your date in for in loop, you'll see that date is actually the index of the element.
var appDate = ['2018/8/22 13:52', '2018/5/11 22:36', '2018/7/20 07:13', '2018/5/30 04:04', '2018/3/26 18:21', '2019/3/20 17:46', '2019/3/18 13:01', '2019/3/18 07:27', '2019/3/17 23:10', '2019/3/17 20:39' ]
let nDates = [];
for(let date in appDate){
console.log(date); // 0 1 2 3 4 5 6 7 8 9
var d = new Date(date);
nDates.push(d);
}
You can use for..of or any other for loop or map to get the converted dates.
Now that you've updated the question, please verify that the dates array contains valid dates by logging them in the loop.

Date Comparison Using Javascript [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I have two date strings in DDMMYYYY format. say startdate="18/02/2013" and enddate ="26/02/2013".
How can I compare these dates. I want enddate to be greater than or equal to startdate
Thanks for Your Time.
I'm a fan of moment.js and consider it a core part of my toolkit whenever I have to deal with dates and times - especially when any form of parsing or formatting is involved.
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}
Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc :
month : Integer value representing the month, beginning with 0 for January to 11 for December.
var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}

Categories