javascript add variable time to date and time - javascript

I need to create a new date/time string based on some variabeles. But I'm not sure how I could do this, I've been searching a bit but can't really find a solution.
var fields = 5; //Fields can vary from 1 tot 999;
var currenttime = $("#serverTime").text().split(":"); //format: 23:02:59
var timetoadd = 5*30 // 150 minutes
var totalseconds = currenttime[0]*3600 + currenttime[1]*60 + currenttime[2] + timetoadd*60;
var currentdate = new Date();
Any help would be much appreciated.

Type cast it:
var totalseconds = parseInt(currenttime[0])*3600 + parseInt(currenttime[1])*60 + parseInt(currenttime[2]) + timetoadd*60;
To get new date:
var t = new Date(1970,0,1);
console.log(t.setSeconds(totalseconds));

Related

Calculate age in JS given the birth date in "dd/mm/yyyy" format

I am trying to write a function in JavaScript to calculate age.
I wrote a function but it does not give accurate age.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], [1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
I try calculateAge("25/11/1993") and I don't get accurate age. Kindly guide me.
You missed the formattedDate for [1] in the new Date() function, so formattedDate[1] it should be.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], formattedDate[1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
var age = calculateAge('25/11/1993');
console.log('My age is', age);

Converting integer to HH:MM:SS

I'm trying to merge two separate integers and convert into a 24 hour format hh:mm:ss. Below is my code:
var hr = 5;
var min = 30;
/**convert to hh:mm:ss*****/
var combine_time = new Date(hr + ":" + min + ":" + "00");
alert(combine_arrive);
However, my javascript show it as invalid date. Can anyone guide me? Thank you
Perhaps you meant this?
We cannot know if 5 is 5am (05) or pm (17) unless you tell us
const arrive_hr = 5;
const arrive_min = 30;
const pad = num => ("0"+num).slice(-2);
const combine_time = `${pad(arrive_hr)}:${pad(arrive_min)}:00`;
console.log(combine_time)
var hr = 5;
var min = 30;
var timeString = `${hr}:${min}:00`
var combine_time = Date.parse('1970-01-01 ' + timeString);
alert(combine_time);
Take a look at the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Use the setter functions.
var hr = 5;
var min = 30;
var combine_time = new Date(); // create new Date and assign value
// as follows you set hr, min and secs
combine_time.setHours(hr);
combine_time.setMinutes(min);
combine_time.setSeconds(0);

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;
}

Adjust file created date value for date between evaluation using Google Apps Script

I want to look at the file created date instead of the current date and add 6 days so my between code will work properly.
var dateFrom = file.getDateCreated();
var dateTo = new Date();
dateTo.setDate(dateTo.getDate() + 6).toString();
var dateCheck = new Date();
dateCheck.setDate(dateCheck.getDate()).toString();
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
// alert("do something");
I have made a few attempts
var dateTo = (file.getDateCreated() + 7).toString();//failed attempt 1
var dateTo = new Date();
dateTo.setDate(dateTo.file.getDateCreated() + 6).toString();//failed attempt 2
var dateTo = new Date();
dateTo.setDate(dateTo.file.getDateCreated() + 6);//failed attempt 3
I am hoping someone can help me learn how to find success.
Regards,
Chris
This code determines whether today's date is at or past a target date. The target date is 6 days past the file creation date:
function olderThan() {
var file = DriveApp.getFileById('Your file ID');
var myFileDate = file.getDateCreated();
var creationDate = new Date(myFileDate);
var now = new Date();
var dateTo = new Date();
dateTo.setDate(creationDate.getDate() + 6);
if (now >= dateTo) {
Logger.log('its older than 6 days old');
};
};

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