Javascript Date -> numeric vs string - javascript

var date1 = new Date('1900-01-01');
console.log(date1);
Yields:
"Mon Jan 01 1900 01:00:00 GMT+0100 (W. Europe Standard Time)"
var date2 = new Date(1900,1,1);
console.log(date2);
Yields:
"Thu Feb 01 1900 00:00:00 GMT+0100 (W. Europe Standard Time)"
Fiddle
But I don't understand why!

You can see the month difference since when you pass individual components (year, month, day, etc) to the Date object constructor, you have to consider that month parameter should start with 0:
console.log( new Date('1900-01-01').getMonth() ); // 0
Other than Jan/Feb there shouldn't be any differences in dates.
MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

Related

Why do this dates not match?

i have this code which works with dates:
let startDate = new Date(toolOrder.jsAppStartDate.getTime()); // clone date
startDate.setDate(startDate.getDate() - Math.floor((days - 1) / 2)); // sub some days
console.log(toolOrder.jsAppStartDate); // Output: Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
console.log(toolOrder.jsAppStartDate.getTime()); // Output: 1695247200000
console.log("--------------");
for (let index = 0; index < days; index++)
{
console.log(startDate);
console.log(startDate.getTime());
// ... some drawing code here ...
startDate.setDate(startDate.getDate() + 1); // add one day
if(startDate === toolOrder.jsAppStartDate) // check if start date reached
{
console.log("Dates match");
startDate = new Date(toolOrder.jsAppEndDate.getTime());
}
}
The output of the log before the loop is:
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
---------------
The output from the loop is:
Date Mon Sep 18 2023 00:00:00 GMT+0200 (Central European Summer Time)
1694988000000
Date Tue Sep 19 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695074400000
Date Wed Sep 20 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695160800000
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
Date Fri Sep 22 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695333600000
So even if the dates match in loop 3, the if condition is not true. It works when I use
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
but I thought it should work without also?
=== compares identity so:
startDate === toolOrder.jsAppStartDate
Means: is startDate the same object [in memory] as toolOrder.jsAppStartDate which is not the case because toolOrder.jsAppStartDate is a different object and not the object referred to by the name startDate.
mdn says this about the strict equality operator:
If both operands are objects, return true only if they refer to the same object.
(emphasis mine)
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
Works because you're now comparing numbers instead of objects.
The rule for the two operands being numbers is:
Otherwise, compare the two operand's values:
Numbers must have the same numeric values. +0 and -0 are considered to be the same value.
mdn (emphasis mine)
You are comparing Date instances with each other when you're using the === operator. However, they are not the same instance. Each new Date creates a unique, new instance (unless the class constructor deliberately returns a previously created instance [for more info: singleton pattern]).
When you are comparing each instance's getTime() result, you are comparing 2 primitive values (numbers in this case). Primitive values are not class instances; so === works like == with primitives.

How to create function that return a Date object?

1 - Make a function that given a date in text format "dd/mm/yyyy" returns a Date object with that date, using the Split() method.
2 - You have to do a "console.log() of the Date object created" and it should output something similar to
Mon Dec 2 2019 11:36:25 GMT+0100 (Central European Standard Time).
I have tried this but I don't know why when I write a console.log
I get the following:
2022-12-05T00:00:00.000Z
And I try to get it to appear something like this:
Mon Dec 2 2019 12:30:05 GMT+0100 (Central European Standard Time)
function convertDate(date) {
let dateArray = date.split("/");
let DateString = dateArray[2] + "/" + dateArray[1] + "/" + dateArray[0] + "Z";
let dateDate = new Date(dateString);
return dateDate;
}
console.log(convertDate("05/12/2022"));
you can use new Date() to get the date like "Wed Dec 28 2022 11:36:25 GMT+0100"
let date = new Date("05/12/2022");
console.log(date);
output will be Thu May 12 2022 00:00:00 GMT+0500 (Pakistan Standard Time) {}

Convert all dates in an array to format MM/DD/YYYY javascript

I have an array of dates in the format :
dates_arr = [
Thu Aug 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
Fri Aug 14 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
Sat Aug 15 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
Sun Aug 16 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
]
I would like to convert all the dates to the format MM/DD/YYYY and replace the array with them.
I would like to convert all the dates to the format MM/DD/YYYY and
replace the array.
You could do it as follows -
Correct Code -
let dates_arr = [
'Thu Aug 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
'Fri Aug 14 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
'Sat Aug 15 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
'Sun Aug 16 2020 00:00:00 GMT-0400 (Eastern Daylight Time)'
];
dates_arr = dates_arr.map((element) => {
var d = new Date(element);
return `${d.getMonth()+1}/${d.getDate()}/${d.getFullYear()}`;
})
console.log("Dates in the format MM/DD/YYYY : \n", dates_arr);
Explanation :
The strings which are present in dates_arr are the default way in which Javascript will output the dates. We are taking each of those strings and mapping over the dates_arr using map() function and simply returning the dates in the required format. This will create a new array with strings of date in the form we need them to be.
Firstly, I am creating a date object in the code using new Date(element). The Date() constructor can take in date string and form date object on which we can apply various in-built methods provided by JS as given below.
There are different methods which date provides us like
getMonth() which returns the month from 0-11
getDate() which returns the day of the month from 1-31 and
getFullYear() which returns the year in the date.
I have used these methods to get the date string into the desired format. There are various other methods as well which you can read more on here.
Also, if you are not aware, I am using template literals in the return statement which is just a syntactic sugar added in ES6. The return statement does the same thing as -
return ((d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear())
But using the template literals is just a more efficient way of writing such statements.
var formattedDate = dates_arr.map(date=>dateFormat(date));
function dateFormat(date){
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit' })
const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date )
return `${month}/${day}/${year}`
}

Js new Date() creates different GMT

I'm reading data from a API server:
opTMP:
{ DATAI: "2019-10-27T00:00:00", …}
{ DATAI: "2019-10-31T00:00:00", …}
then I create a new date:
const opTMP1 = this.opTMP.map(x => Object.assign({}, x));
for (const op of opTMP1){
let d = new Date(op.DATAI);
console.log(d);
...
}
but in console I got different results,one is GMT+0300 and one GMT+0200 :
d: Sun Oct 27 2019 00:00:00 GMT+0300 (Eastern European Summer Time)
d: Thu Oct 31 2019 00:00:00 GMT+0200 (Eastern European Standard Time)
because of that I got problems when comparing it,I want to get only day month and year,no time info needed,how can I reset both to the same time or to 0:00:00?
Converting date to epoch time is good way to comparing the dates.
let d = new Date(op.DATAI).getTime();

Find max date from a string array of dates using max function of date-fns

Dates string array is constructed from backend data object as below:
const dates: string[] = this.data.map((item:any) => item.date.jsdate);
The result is
dates = [
Thu Jan 12 2015 00:00:00 GMT+0530 (India Time),
Tue Feb 25 2015 00:00:00 GMT+0530 (India Time),
Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)
]
typeof(dates) is "object"
How to find the get the latest date among the jsdates array?
Is it possible to apply max function of date-fns?
I can offer one solution, using the momentjs (https://momentjs.com/) library.
You can sort the dates using:
dates = dates.sort((a,b) => moment(a).diff(moment(b));
Then if you want the latest date you could take the last element from that array:
return dates[dates.length-1];
You should also be able to do this without moment:
dates = dates.sort((a,b) => new Date(b) - new Date(a));
Convert each to a Date object and compare using getTime() function.
var dates = [
'Thu Jan 12 2015 00:00:00 GMT+0530 (India Time)',
'Tue Feb 25 2015 00:00:00 GMT+0530 (India Time)',
'Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)'
]
console.log(
dates.sort((a,b)=>new Date(b).getTime() - new Date(a).getTime())[0]
)

Categories