How to calculate time from now in javascript? - 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;
}

Related

How to get minutes in between two different dates?

Hi i am using Javascript and i want to get each and every minute between two dates for example:
firstDate: 2019-04-02 02:03:00
secondDate: 2019-04-03 03:04:00
So my final output result should return like this:
2019-04-02 02:03:00
2019-04-02 02:04:00
2019-04-02 02:05:00
.
.
.
2019-04-03 03:04:00
Here is the code which i tried
var boxingDay = new Date("2019-04-02 02:03:00");
var nextWeek = new Date("2019-04-03 03:04:00");
function getDatesRange(startDate, stopDate){
const ONE_DAY = 60*1000;
var days= [];
var currentDate = new Date(startDate);
while (currentDate <= stopDate) {
days.push(new Date (currentDate));
currentDate = currentDate - 1 + 1 + ONE_DAY;
}
return days.join("\n");
}
console.log(getDatesRange(boxingDay,nextWeek))
/* var map = getDates(boxingDay, nextWeek).map((times) => {
console.log(Date.parse(times))
}) */
/* console.log((getDates( boxingDay, nextWeek ))); */
The problem is I am getting correct output but I need in the form of an array, like below and reuse the function if I am reusing, it returns me an empty array.
[[2019-04-02 02:03:00],[2019-04-02 02:04:00].....]
Any solution TIA.
Using your code as a basis, you can do this as follows (note that I'm using .toISOString(), you can change this according to your needs):
const boxingDay = new Date("2019-04-02 02:03:00");
const nextWeek = new Date("2019-04-03 03:04:00");
function getDatesRange(startDate, stopDate){
const ONE_MINUTE = 60*1000;
const days= [];
let currentDate = new Date(startDate);
while (currentDate <= stopDate) {
days.push([currentDate.toISOString()]);
currentDate.setTime(currentDate.getTime() + ONE_MINUTE);
}
return days;
}
console.log(getDatesRange(boxingDay,nextWeek));
There is a way, that you could use while loop with format function, each iteration increate the minute
const firstDate = new Date('2019-04-02 02:03:00')
const secondDate = new Date('2019-04-03 03:04:00')
const formatDate = dateObj => {
const year = String(dateObj.getFullYear()).padStart(4, '0')
const month = String(dateObj.getMonth() + 1).padStart(2, '0')
const date = String(dateObj.getDate()).padStart(2, '0')
const hour = String(dateObj.getHours()).padStart(2, '0')
const minute = String(dateObj.getMinutes()).padStart(2, '0')
const second = String(dateObj.getSeconds()).padStart(2, '0')
return `${year}-${month}-${date} ${hour}:${minute}:${second}`
}
const res = []
const iteratedDate = new Date(firstDate.getTime())
while (iteratedDate <= secondDate) {
res.push(formatDate(iteratedDate))
iteratedDate.setMinutes(iteratedDate.getMinutes() + 1)
}
// res array is large so I sliced the first 10 amd the last 10
console.log(res.slice(0, 10))
console.log(res.slice(res.length - 10))
A slightly different approach using a for loop; it also avoids creating a new Date instance for each minute iterated.
const p = new Date("2019-04-02T23:57:00");
const q = new Date("2019-04-03T00:03:00");
const r = [];
for(const d = new Date(p); d <= q; d.setTime(d.getTime() + 60000))
{
r.push(d.toISOString().substring(0, 19).replace(/T/, " "));
}
const s = r.join("\n");
console.log(s);

How to get the time difference between two times in Javascript?

I have two times, say timeS = '00.00.00' and timeE = '10.00.00'
I want to get the time difference between the two times. One way is the following manner,
//create date format
var timeStart = new Date("01/01/2007 " + timeS).getHours();
var timeEnd = new Date("01/01/2007 " + timeE).getHours();
var hourDiff = timeEnd - timeStart;
Here, I had to get the desired result using the Date format. Is there any other way to achieve this, without explicitly making a Date object?
Note: Instead of marking it a duplicate, do observe that I am asking for some other alternative ways.
Convert the hh.mm.ss format into equivalent seconds by parsing.
var timeS = '00.00.00';
var timeE = '10.00.00';
function convertToSeconds(timeString) {
var timeSplit = timeString.split('.');
return timeSplit.reduce((result, item, index) => {
return result + Number(item) * Math.pow(60, timeSplit.length - index - 1)
}, 0);
}
const secondDifference = convertToSeconds(timeE) - convertToSeconds(timeS);
console.log(secondDifference);
You need to convert this time to a Date first
var convertToMS = time => {
var d = new Date(1,1,1);
d.setHours.apply( d, time.split(".").map( Number ) );
return d.getTime();
};
var diffOutput = convertToMS( timeE ) - convertToMS( timeS );
Demo
var convertToMS = time => {
var d = new Date();
d.setHours.apply(d, time.split(".").map(Number));
return d.getTime();
};
var timeS = '00.00.00';
var timeE = '10.00.00';
var diffOutput = convertToMS(timeE) - convertToMS(timeS);
console.log(diffOutput)
Edit
As suggested by #RobG, check this alternate solution using UTC
var convertToMS = time => Date.UTC(1,1,1, ...time.split('.'));

Calculating array of dates

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')
}

How to add continuously some Minutes to the time string and generate new time

i have a start Time and end time in string. i have split start time (time string format "05:30:00")
var dateArray = data.start_time.split(":");
var firstHour = dateArray[0];
var firstMinutes = dateArray[1];
var firstSec = dateArray[2];
now i want to Add 80 minutes to this time and want generate a new time (push in a array) , then i want to add it again n again to a end time limit how it is possible?
why not use check:
var slog=80;
var firstHour = dateArray[0];
var firstMinutes = dateArray[1];
var firstSec = dateArray[2];
if(slog%60 != 0){// when slog is not fixed
firstHour=firstHour+slog/60;
firstMinutes=firstMinutes+slog%60;
}else if(slog%60 == 0){
firstHour=firstHour+slog/60;
}
From the top of my head (not tested!):
yourTime = startTime;
while(yourTime < endTime){
yourTime.setMinutes(yourTime.getMinutes() + 80);
dateArray.push(yourTime);
}
var d = new Date();
var theDate = d.getFullYear() + '-' + ( d.getMonth() + 1 ) + '-' + d.getDate();
var theTime = theDate + " 15:00:00";
var newTime = new Date( Date.parse( theTime ) + 80*60*1000 );

Javascript / jQuery two datepickers calculate date range

I use the Javascript below to calculate days out of a date range (2 Zebra Datepickers) and to pass the value to input field 'nights' .. then process a form.
While my Javascript works fine, i fail to achieve the same result with jQuery .val()
Javascript:
setDifference = function(form)
{
var x = document.getElementById('startDate').value;
var y = document.getElementById('endDate').value;
var arr1 = x.split('-');
var arr2 = y.split('-');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
document.getElementById('nights').value = (dt2.valueOf() - dt1.valueOf()) / (60 * 60 * 24 * 1000)
}
jQuery i tried so far:
$(function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var dateSplit = startDate.split("-");
var dateSplit = endDate.split("-");
dateDiff = new Date(dateSplit[1] + " " + dateSplit[0] + ", " + dateSplit[2]);
var dateDiff = new Date(endDate - startDate);
var days = dateDiff/1000/60/60/24;
$('#nights').val(days);
});
Error i get is either 'NaN or 'invalid date' on all browsers i tried.
You have declared dateSplit two times. hence startdate and enddate would be same.

Categories

Resources