Converting date array with getTime() - javascript

this is a snippet of code from a project I am doing, I have to convert dates using to getTime() function and push them into a new array, however everytime i do however the new array prints as NaN, i was hoping to gain some insight on what i was doing wrong and how to fix this issue. Thanks a ton :)
dates = ["28/7/2020", "28/3/2020", "28/1/2020", "28/10/2020"]
// const MAX = dates[0]
// const MIN = dates[dates.length - 1];
const dateArr = [];
const DAY_IN_MS = 24 * 60 * 60 * 1000
for (i = 0; i < dates.length; i++) {
d = new Date(dates[i])
dateInMs = d.getTime();
parseInt(dateInMs);
console.log(dateInMs);
dateArr.push(dateInMs);
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>

you have to switch the day and month otherwise new Date will return invalid date
example:
const d = "28/7/2020";
const dateSplit = d.split("/")
new Date(`${dateSplit[1]}/${dateSplit[0]}/${dateSplit[2]}`)
will return: Tue Jul 28 2020 00:00:00 GMT+0200 (Central European Summer Time)
What you could do is replace your New date line with the following:
const dateSplit = dates[i].split("/")
const newDate = new Date(`${dateSplit[1]}/${dateSplit[0]}/${dateSplit[2]}`)
d = new Date(newDate)
Either that or try to change the initial format to something new Date can Handle. This will prevent of having to split and add extra code
EDIT: To get the amount of days between first and last date. Here is an example:
const minutes = 1000*60;
const hours = minutes*60;
const days = hours*24;
const date1 = new Date("7/28/2020").getTime();
const date2 = new Date("10/28/2020").getTime();
const dateDiff = Math.round((date2 - date1)/days);
console.log(dateDiff);
EDIT 2: to get the difference in length you would do this (using the dates you mentioned in your comment):
const dateArr = [];
let date1 = ("23/9/2020").split("/");
let date2 = ("29/9/2020").split("/");
const diffDays = date2[0] - date1[0]; // date1[0] = 23, date2[0] = 29
for (i = 0; i <= diffDays; i++) {
// content of the push would save each day between 23 and 29 as value... you can put whatever in here
dateArr.push(`${date1[0] + i}/9/2020`);
}
console.log(dateArr.length); // should equal 7

3 lines in your javascript code are missing semicolons. My suggestion is to review your code a bit more carefully before posting, and also review the syntax for the various javascript date functions. This should work:
const dates = ["28/7/2020", "28/3/2020", "28/1/2020", "28/10/2020"];
var dateArr = [];
var DAY_IN_MS = 24 * 60 * 60 * 1000;
for (i = 0; i < dates.length; i++) {
// format your date string properly for Date()
var tmp = dates[i].split('/');
// convert the string to a date
var d = new Date( tmp[2], tmp[1], tmp[0] );
console.log( dates[i] );
console.log( d );
dateInMs = d.getTime();
parseInt(dateInMs);
console.log(dateInMs);
dateArr.push(dateInMs);
}

Related

Google App Scripts - Getting a constant "Yesterday"

I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts).
I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked.
I'm pretty sure it should be a minor change but I cannot figure out how to solve this.
A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));
Your issue is that today is not a Date object, because you've called Utilities.formatDate on it. This is why you are getting an error when trying to use today.setDate(). So you need to use another variable to allow you to compute yesterday. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1) sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate) and subtract 1 from that to get yesterday's date.
getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},
function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object

How to get time using toDate() and not format() [duplicate]

how can i extract time from datetime format.
my datetime format is given below.
var datetime =2000-01-01 01:00:00 UTC;
I only want to get the time 01.00 as 01
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
Date.prototype.toLocaleTimeString()
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
var time = datetime.toLocaleTimeString();
Update:
The new locales and options arguments let applications specify the
language whose formatting conventions should be used and customize the
behavior of the function. In older implementations, which ignore the
locales and options arguments, the locale used and the form of the
string returned are entirely implementation dependent.
// Depending on timezone, your results will vary
var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
What about these methods
new Date().getHours()
new Date().getMinutes()
For example:
var d = new Date();
var n = d.getHours();
Edited
Return the hour, according to universal time:
new Date().getUTCHours()
Example:
var d = new Date();
var n = d.getUTCHours();
As an alternative if you want to get the time from a string -
var datetime ="2000-01-01 01:00:00 UTC";
var myTime = datetime.substr(11, 2);
alert(myTime) //01
with the moment.js library it works in this way:
var result = moment().format('hh');
alert(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
var datetime = ("2000-01-01 01:00:00 UTC");
var d1 = new Date(datetime);
var minute = d1.getUTCMinutes();
var hour = d1.getUTCHours();
if(minute > 0)
alert(hour+"."+minute);
else
alert(hour);
Demo
var date1 = new Date(1945,10,20, 17,30)
var date2 = new Date(1970,1,8, 12,00)
console.log(date1.getHours() - 8 + (date1.getMinutes()/60))
console.log(date2.getHours() - 8 + (date2.getMinutes()/60))
Use the following code:
var datetime = "2000-01-01 01:00:00 UTC";
var dt = new Date(datetime);
var hr = dt.getUTCHours();
if(hr > 12) {
hr -= 12;
}
alert(hr);
refer this link also.
I have done it! It looks like this:
console.log(new Date().toLocaleTimeString() + " " + new Date().getSeconds() + " seconds");
Assuming you have a Date object like
var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
// or
var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
then use the getUTCHours method:
datetime.getUTCHours(); // 1
I hope you can find a solution here.
let preDateTime = new Date("2022-03-31 22:26:00");
let newTime = preDateTime.toLocaleTimeString('en-US');
let hour = newTime.split(":")[0];
let amPm = newTime.split(" ")[1];
let seconds = newTime.split(":")[2].replace(amPm,'');;
let noAmPm = newTime.replace(amPm,'');
let noAmPmSeconds = noAmPm.replace(":"+seconds,'');
let noSeconds = newTime.replace(":"+seconds,' ');
if(parseInt(hour)<9){
newTime = "0"+newTime;
noAmPm = "0"+noAmPm
noSeconds= "0"+noSeconds
noAmPmSeconds = "0"+noAmPmSeconds;
}
console.log(newTime); //10:26:00 PM
console.log(noAmPm); //10:26:00
console.log(noSeconds); //10:26 PM
console.log(noAmPmSeconds); //10:26

Creating an array of dates between 2 dates

I have 2 dates: startdate and enddate. End date is always a day less than the startdate. So if my start day is 19th, the end date would be on the 18th of next month.
I am trying to create an array of number of days in between the 2 dates.
(It goes from 19th to 18th and then 18th to 18th of every month to calculate the difference)
Example
8/19/2018 - 9/18/2018 = 30 days
9/18/2018 - 10/18/2019 = 30 days
10/18/2018 - 11/18/2018 = 31 days
array = [30,30,31]
I am using the following code to calculate days difference between the dates.
function daysBetweenArrears (date1, date2){
date1.setDate(date1.getDate() );
date2.setDate(date2.getDate() - 1);
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
The following code for creating the array
if (document.getElementById("endDate"))
y = document.getElementById("endDate").value;
if (document.getElementById("startDate"))
z = document.getElementById("startDate").value;
var dateArr = getDateArray(z, y);
var dayCountArr = "";
var b = [];
for (var x = 0; x < dateArr.length-1; x++)
{
dayCountArr += daysBetweenArrears(dateArr[x], dateArr[x+1], ",");
b.push(daysBetweenArrears(dateArr[x], dateArr[x+1]));
}
The issue is that when i set the date as following, it is giving me incorrect output. The problem is that it is setting the dates incorrectly whenever it goes to the next month. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
date2.setDate(date2.getDate() - 1);
You can do this using moment. Hope this helps.
const start = "8/19/2018";
const end = "11/18/2018 ";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : 0);
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can update your function daysBetweenArrears
const daysBetweenArrears = (date1, date2) => {
const time1 = new Date(date1).getTime();
const time2 = new Date(date2).getTime();
const diff = Math.abs(time2 - time1);
return Math.round(diff/(1000*60*60*24));
};
console.log(daysBetweenArrears('8/18/2018', '9/18/2018'));
console.log(daysBetweenArrears('6/18/2018', '7/18/2018'));

Create array of dates from starting date in JavaScript and React

I have a React component where I have a date string from which I need to generate an array of dates representing the next 11 days excluding the starting date (10/12/2016). Not sure how to achieve this. That's what I've tried so far but the problem is that by simply looping adding 1 for each iteration on the day, it won't generate the correct date when the date range of 11 days spans between two months:
addDays = () => {
const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
const date = new Date(startDate);
let datesCollection = []
for (var i = 1; i < 12; i++) {
datesCollection.push(`${date.getDate() + i}/${date.getMonth() + 1}/${date.getFullYear()}`)
}
return datesCollection
}
The code above generates the following array:
[
"11/12/2016",
"12/12/2016",
"13/12/2016",
"14/12/2016",
"15/12/2016",
"16/12/2016",
"17/12/2016",
"18/12/2016",
"19/11/2016",
"20/12/2016",
"21/12/2016"
]
How do I generate the correct array, with proper dates for each month?
You can simply do that:
addDays = () => {
const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
const date = new Date(startDate);
let datesCollection = []
for (var i = 1; i < 12; i++) {
const newDate = new Date(date.getTime() + i * 1000 * 60 * 60 * 24);
datesCollection.push(`${newDate.getDate()}/${newDate.getMonth() + 1}/${newDate.getFullYear()}`);
}
return datesCollection
}
You can try adding 1 day to each loop.
var dateuse = new Date();
dateuse.setDate(dateuse.getDate() + 1);
or you can try Moment.js
var today = moment();
var dateuse = moment(today).add(1, 'days');

extract time from datetime using javascript

how can i extract time from datetime format.
my datetime format is given below.
var datetime =2000-01-01 01:00:00 UTC;
I only want to get the time 01.00 as 01
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
Date.prototype.toLocaleTimeString()
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
var time = datetime.toLocaleTimeString();
Update:
The new locales and options arguments let applications specify the
language whose formatting conventions should be used and customize the
behavior of the function. In older implementations, which ignore the
locales and options arguments, the locale used and the form of the
string returned are entirely implementation dependent.
// Depending on timezone, your results will vary
var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
What about these methods
new Date().getHours()
new Date().getMinutes()
For example:
var d = new Date();
var n = d.getHours();
Edited
Return the hour, according to universal time:
new Date().getUTCHours()
Example:
var d = new Date();
var n = d.getUTCHours();
As an alternative if you want to get the time from a string -
var datetime ="2000-01-01 01:00:00 UTC";
var myTime = datetime.substr(11, 2);
alert(myTime) //01
with the moment.js library it works in this way:
var result = moment().format('hh');
alert(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
var datetime = ("2000-01-01 01:00:00 UTC");
var d1 = new Date(datetime);
var minute = d1.getUTCMinutes();
var hour = d1.getUTCHours();
if(minute > 0)
alert(hour+"."+minute);
else
alert(hour);
Demo
var date1 = new Date(1945,10,20, 17,30)
var date2 = new Date(1970,1,8, 12,00)
console.log(date1.getHours() - 8 + (date1.getMinutes()/60))
console.log(date2.getHours() - 8 + (date2.getMinutes()/60))
Use the following code:
var datetime = "2000-01-01 01:00:00 UTC";
var dt = new Date(datetime);
var hr = dt.getUTCHours();
if(hr > 12) {
hr -= 12;
}
alert(hr);
refer this link also.
I have done it! It looks like this:
console.log(new Date().toLocaleTimeString() + " " + new Date().getSeconds() + " seconds");
Assuming you have a Date object like
var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
// or
var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
then use the getUTCHours method:
datetime.getUTCHours(); // 1
I hope you can find a solution here.
let preDateTime = new Date("2022-03-31 22:26:00");
let newTime = preDateTime.toLocaleTimeString('en-US');
let hour = newTime.split(":")[0];
let amPm = newTime.split(" ")[1];
let seconds = newTime.split(":")[2].replace(amPm,'');;
let noAmPm = newTime.replace(amPm,'');
let noAmPmSeconds = noAmPm.replace(":"+seconds,'');
let noSeconds = newTime.replace(":"+seconds,' ');
if(parseInt(hour)<9){
newTime = "0"+newTime;
noAmPm = "0"+noAmPm
noSeconds= "0"+noSeconds
noAmPmSeconds = "0"+noAmPmSeconds;
}
console.log(newTime); //10:26:00 PM
console.log(noAmPm); //10:26:00
console.log(noSeconds); //10:26 PM
console.log(noAmPmSeconds); //10:26

Categories

Resources