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('.'));
Related
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);
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;
}
Say I have a number x that can be anything (within reason). How would I create a new Date object that is x number of seconds ago? I have no idea about how to approach this.
var seconds = 5;
var dateNow = new Date();
var date5SecondsAgo = new Date(dateNow.getTime() - seconds*1000);
var now = new Date();
var seconds = 15;
var before = new Date(now.getTime() - seconds*1000);
You can use the valueOf/getTime property to get the the number of milliseconds since Jan 1, 1970 and then there are 1,000 milliseconds in a seconds
var milliSecondPerSecond = 1000;
var myStartDate = new Date(myEndDateTime - numberOfSeconds * milliSecondPerSecond );
Here's a function to do this, which I'm using in a real project. I used Date.now() and provided a second parameter to make it easy to test.
export const backDate = (secondsAgo: number, now: number = Date.now()): Date =>
new Date(now - secondsAgo * 1000)
Here's a version without the typescript noise.
export const backDate = (secondsAgo, now = Date.now()) =>
new Date(now - secondsAgo * 1000)
You can call it without the now parameter to get what you want.
const thirtySecondsAgo = backDate(30)
I want to pick up date from screen, add 1 day and put back to screen.
<input type='text'value='20101231' id='from_date'>
<script>
function date_move(direction){
var from_date = document.getElementById('from_date').value;
var YYYY = from_date.substring(0,4);
var MM = from_date.substring(4,6);
var DD = from_date.substring(6,8);
var jsCurDate = new Date( parseInt(YYYY,10), parseInt(MM,10)-1, parseInt(DD,10) );
var newDate = addOrSubtracDays(jsCurDate,direction)
document.getElementById('from_date').value = newDate;
}
function addOrSubtracDays(jsCurDate,daysOffset){
var daylength= 1*24*60*60*1000;
var newDate = new Date(jsCurDate + daylength);
alert(newDate)
}
date_move(+1);
</script>
You can't use element.value to get the contents of an arbitrary HTML element, .value only works on form elements. Use element.innerHTML instead:
var from_date = document.getElementById('from_date').innerHTML;
Also, your use of substring is wrong. I think substr is more clear:
var YYYY = from_date.substr(0,4);
var MM = from_date.substr(4,2);
var DD = from_date.substr(6,2);
In addOrSubtracDays (shouldn't that be addOrSubtractDays?) you want the number of milliseconds, so you should call Date.getTime. Moreover, you actually want to return the new value:
return new Date(jsCurDate.getTime() + daylength * daysOffset);
When changing #from_date you probably want your date to be in the same format. For this, I extend Date's prototype with a new method (and String with a helper function):
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
Date.prototype.toFormattedString = function () {
return [String(this.getFullYear()),
String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0')].join('');
};
After this, we can simply call toFormattedString:
document.getElementById('from_date').innerHTML = newDate.toFormattedString();
BTW, you don't need to explicitly convert YYYY, MM and DD to integers with base 10; those are converted automatically (without assuming a string beginning with 0 is an octal number):
var jsCurDate = new Date(YYYY, MM - 1, DD);
For the sake of clarity, the complete script now reads:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
Date.prototype.toFormattedString = function () {
return [String(this.getFullYear()),
String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0')].join('');
};
function date_move(direction){
var from_date = document.getElementById('from_date').innerHTML;
var YYYY = from_date.substr(0,4);
var MM = from_date.substr(4,2);
var DD = from_date.substr(6,2);
var jsCurDate = new Date(YYYY, MM - 1, DD);
var newDate = addOrSubtracDays(jsCurDate, direction);
document.getElementById('from_date').innerHTML = newDate.toFormattedString();
}
function addOrSubtracDays(jsCurDate, daysOffset){
var daylength= 1*24*60*60*1000;
return new Date(jsCurDate.getTime() + daylength * daysOffset);
}
date_move(+1);
From my understanding the only thing you are missing in that code is:
function addOrSubtracDays(jsCurDate,daysOffset){
var daylength= 1*24*60*60*1000;
var newDate = new Date(jsCurDate+(daylength*daysOffset));
document.getElementById('from_date').value = newDate; //<-THIS LINE
}
EDIT: Sorry I read badly... never mind
How can i time how much time passes between 2 events with javascript? like, to the millisecond?
When performing arithmetic operations on Date objects, they are implicitly converted to milliseconds (since 1970-01-01 00:00:00 UTC), so all you need to do is subtract a Date created when the operation started from a Date created when the operation ends.
var start = new Date();
doSomeHeavyWork();
var end = new Date();
var millisecondsElapsed = end - start;
Easiest way to do this.
console.time("timer name")
console.timeEnd("timer name")
This will output the time in milliseconds to the console.
It's surprisingly difficult to do.
var start = new Date();
// Do things here
var finish = new Date();
var difference = new Date();
difference.setTime(finish.getTime() - start.getTime());
alert( difference.getMilliseconds() );
Well, you can use firebug (firefox plugin) to benchmark your functions. Check this article : benchmark javascript funcions
What about making a reusable timer object?
Usage:
// event 1
document.getElementById('elId').onclick = function () {
timer.start('myTimer1');
};
// event 2
document.getElementById('otherElement').onclick = function () {
alert(timer.stop('myTimer1')); // alerts the time difference in ms
};
Implementation:
var timer = (function () {
var startTimes = {}; // multiple start times will be stored here
return {
start: function (id) {
id = id || 'default'; // set id = 'default' if no valid argument passed
startTimes[id] = +new Date; // store the current time using the timer id
},
stop: function (id) {
id = id || 'default';
var diff = (+new Date - startTimes[id]); // get the difference
delete startTimes[id]; // remove the stored start time
return diff || undefined; // return the difference in milliseconds
}
};
}());
var initialTime = (new Date).getTime(), i = 55000;
(function() {
while ( i-- ) {
setTimeout( function(){}, 20 );
}
})()
var finalTime = ( new Date ).getTime(), diff = (new Date);
diff.setTime( finalTime - initialTime );
alert( diff.getMilliseconds() + 'ms' )