Calculating array of dates - javascript

I'm trying to convert an array of days:
['1','2','3','4','5']
to an array of dates which are today +1 day , today +2 etc
I have:
interval_dates = []
var intervals = rows[index+1][0].split(',')
var now = new Date();
for (i in intervals){
// add a day
interval_dates.push(now.setDate(now.getDate() + intervals[i]));
}
Logger.log(interval_dates);
I'm seeing
[1.505998326018E12, 1.522500726018E12, 1.546869126018E12, 1.552654326018E12, 1.564750326018E12], ]
what am I doing wrong?

var dateRange = [];
['1','2','3','4','5'].forEach(function(dayIncrement) {
var date = new Date();
date.setDate(date.getDate() + parseInt(dayIncrement));
dateRange.push(date);
});
console.log(dateRange);

The intervals are string, you need to get the day of today and add the interval after converting it to a number using +interval, so it would be now.getDate() + +intervals[i], then call new Date() on the result, and of course change the loop from i in intervals to a number range:
var intervals = ['1','2','3','4','5'];
var interval_dates = [];
var date;
for (var i=0; i<intervals.length; i++){
// add a day
date = new Date();
interval_dates.push(new Date(date.setDate(date.getDate() + +intervals[i])));
}
console.log(interval_dates);

function arrayOfDays()
{
var dayA=[1,2,3,4,5];
var today=new Date().setHours(0,0,0,0);
var day=24*60*60*1000;
var days=[];
for(var i=0;i<dayA.length;i++)
{
days.push(Utilities.formatDate(new Date(today + (i * day)), Session.getScriptTimeZone(), "MM/dd/yyyy"));
}
//Logger.log(days);
var ui=HtmlService.createHtmlOutput('[' + days.join(', ') + ']');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Array of Days')
}

Related

JS : add date obgectto array

i try to make array of dates ,but when i push the last one all the other dates in the array be the same last one .
var dateArayy=[];
var date = new Date();
function addone(){
date.setDate(date.getDate()+1); //add day to the date
dateArayy.push(date) ;
// i try also dateArayy[dateArayy.lenght]=date THE SAME..
}
for (let i=1;i<10;i++){
addone();
}
console.log(dateArayy)
you change and set the same object in array . you should create new Date object and add it to the array
var dateArayy = [];
var date = new Date();
function addone() {
var newdate = new Date();
newdate.setDate(date.getDate() + 1);
date = newdate;
dateArayy.push(date);
}
for (let i = 1; i < 10; i++) {
addone();
}
console.log(dateArayy);
let dates = [];
for (let i = 0; i < 10; i++) {
let date = new Date();
date.setDate(date.getDate() + i);
dates.push(date);
}
console.log(dates);

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

How to calculate time from now in javascript?

I'm a code newbie so forgive me if the answer to this question is obvious!
I'm collecting JSON data from an API and I have a value, ExpectedDateTime, which I'd like to use to calculate the number of minutes and seconds from now.
It has the format: 2016-05-09T12:26:26
I've tried this:
function applyTimeToVallingby(data) {
$scope.timeToVallingby = 0;
$scope.timeToVallingby2 = 0;
d = new Date();
for(i=0;i<data.ResponseData.Buses.length;i++){
if(data.ResponseData.Buses[i].JourneyDirection === 2){
if($scope.timeToVallingby===0){
$scope.timeToVallingby=(d-data.ResponseData.Buses[i].ExpectedDateTime);
}else if($scope.timeToVallingby!=0&&$scope.timeToVallingby2===0){
$scope.timeToVallingby2=d-data.ResponseData.Buses[i].ExpectedDateTime;
}
}
}
}
But it doesn't work. I've tried to find a way to convert the new Date() value to something similar to the format of ExpectedDateTime, so that I can just subtract, but haven't been able to.
Best regards,
Kind of diff of time :
var date = new Date('2016-05-09T12:26:26');
var now = new Date();
alert(" Seconds from now : " + parseInt( (now.getTime() - date.getTime())/1000 ) );
In your way - d.getTime() - new Date( data.ResponseData.Buses[i].ExpectedDateTime).getTime()
You need to first convert ExpectedDateTime to a Date Object
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
Now simple get the number of Milliseconds difference from now and this expectedDateObj object
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = noOfMS/1000;
var noOfMinAndSec = "Min = " + numberOfSeconds/60 + " Sec = " + numberOfSeconds%60;
DEMO
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = Math.floor(Math.abs(noOfMS/1000));
var noOfMinAndSec = "Min = " + parseInt(numberOfSeconds/60) + " Sec = " + numberOfSeconds%60;
alert( noOfMinAndSec );
Maybe you could use Moment.js library:
$scope.daysLeft = function (end_date) {
var now = moment();
var then = moment(end_date);
var diff = then.diff(now, 'days');
if(diff <= 0)
return 0;
return diff;
}

Pick a date then convert format from UNIX to UTC in yyyymmdd

Objective: Setup the date in the array at the end of the block to read: yyyymmdd including the zeros. (example data build: numDaysAPITimes = [20150403]). What I got is not getting the month correctly and the numDaysAPITimes array is storing only the year for some reason.
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date(backDateEpochTime); //Convert to UTC
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
numDaysAPITimes[i] = (curr_year + curr_month + curr_date);
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
a couple things:
your date info is getting added together as numbers, that why it seems the year is only going through. One way to handle that would be to use the toString() method.
you'll probably want leading zeroes on the day and month, which you can achieve by prepending a 0 and then doing a slice -2.
That would looks like This JSFiddle, or:
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = 2;//document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date((1000*backDateEpochTime)); //Convert to UTC
var curr_date = ("0" + d.getDate()).slice(-2)
var curr_month = ("0"+ (d.getMonth() + 1)).slice(-2); //Months are zero based
var curr_year = d.getFullYear();
console.log(d.getMonth());
numDaysAPITimes[i] = (curr_year.toString() + curr_month.toString() + curr_date.toString());
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
console.log(numDaysAPITimes)

Javascript function , which takes a month/date and disply 12 months/dates back

Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"

Categories

Resources