JavaScript creating a Date Object x seconds Ago? - javascript

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)

Related

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('.'));

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

Convert hours and minute to millisecond using javascript or jQuery

I have Hours:Minute format of time as string. To display it into highchart as time i need to convert this string into milliseconds.
For example: 34:26 (34 hours and 26 minutes) millisecond is 124000000
How can i convert it to milliseconds using any of jquery or javascript function.
Try this code:
const toMilliseconds = (hrs,min,sec) => (hrs*60*60+min*60+sec)*1000;
console.log(toMilliseconds(34, 26, 0)); // --> 123960000ms
This is simple.
var time = "34:26";
var timeParts = time.split(":");
console.log((+timeParts[0] * (60000 * 60)) + (+timeParts[1] * 60000));
Arrow functions + hoisting variation with ES2015:
// Function
const milliseconds = (h, m, s) => ((h*60*60+m*60+s)*1000);
// Usage
const result = milliseconds(24, 36, 0);
// Contextual usage
const time = "34:26";
const timeParts = time.split(":");
const result = milliseconds(timeParts[0], timeParts[1], 0);
console.log(result);
This way you can componetize or make it service

java script calculate time difference

i want to let the user to input the entry and the exit time then calculate the charge base on the hours. What i think is convert the time to minutes and then calculate the difference. Can anyone teach me how to do that?
You first have to parse your dates, e.g. in the constructor of a new Date:
var first = new Date(yourDateAsAString)
var second = new Date(yourOtherDateAsAString)
Then you are able to calculate a difference in days as follows:
var difference = second.getTime() - first.getTime()
These are the milliseconds. Do /1000 for seconds, then /60 for minutes, then /60 for hours and then /24 for the final difference in days.
Try this :
var timestampEntry = new Date(entry_time).getTime();
var timestampExit = new Date(exit_time).getTime();
var delta = timestampExit - timestampEntry;
console.log(delta / 1000 / 60 / 60);
html:
<input id="date1" type="text">
<input id="date2" type="text">
<button id="calculate">calculate!</button>
<span id="result"></span>
javascript:
function calculate() {
var input1 = document.getElementById('date1').value;
var input2 = document.getElementById('date2').value;
var date1 = new Date(input1);
var date2 = new Date(input2);
var result = (date2 - date1) / 1000 / 60 / 60;
document.getElementById('result').innerHTML = result;
}
document.getElementById('calculate').onclick = calculate;
jsfiddle: http://jsfiddle.net/3Z9dM/
Note that you need a full date, you have to know a day.
Also parsing date with the constructor of Date() doesn't work exactly the same in all browser. Be aware of the troll from a big cave.
Based on a 24hr clock:
time = hh:mm
ex: 07:34, 23:22
function calculateHours(start, end) {
var
startHours = parseInt(start.slice(0,2),10),
startMin = parseInt(start.slice(2), 10),
stopHours = parseInt(stop.slice(0,2), 10),
stopMin = parseInt(stop.slice(2), 10),
total
;
total = ((stopHours * 60 + stopMin) - (startHours * 60 + startMin)) / 60;
return total;
}
For sure there are better ways to do such a thing, but this is the function you asked for.
Although this can be done in plain JavaScript, if you are working with and manipulating a lot of date times, you might want to look at moment.js. It makes working with times and timezones a lot better.
You can do some thing like this, i haven't done the form validation
Here is the plunkr link: http://plnkr.co/edit/8wVC1yZeGCmrY0rSXMzL?p=preview
JS stores dates as time in ms since midnight January 1, 1970
So calculating the time between two dates is as simple as subtracting them.
Create a Date() object at two different times.
var time1 = new Date();
var time2 = new Date();
var difference = time2-time1;
var inHours = difference / (1000 * 60 * 60);

How can I get seconds since epoch in Javascript?

On Unix, I can run date '+%s' to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.
Is there a way to find out seconds since Epoch in JavaScript?
var seconds = new Date() / 1000;
Or, for a less hacky version:
var d = new Date();
var seconds = d.getTime() / 1000;
Don't forget to Math.floor() or Math.round() to round to nearest whole number or you might get a very odd decimal that you don't want:
var d = new Date();
var seconds = Math.round(d.getTime() / 1000);
Try this:
new Date().getTime() / 1000
You might want to use Math.floor() or Math.round() to cut milliseconds fraction.
You wanted seconds since epoch
function seconds_since_epoch(){ return Math.floor( Date.now() / 1000 ) }
example use
foo = seconds_since_epoch();
The above solutions use instance properties. Another way is to use the class property Date.now:
var time_in_millis = Date.now();
var time_in_seconds = time_in_millis / 1000;
If you want time_in_seconds to be an integer you have 2 options:
a. If you want to be consistent with C style truncation:
time_in_seconds_int = time_in_seconds >= 0 ?
Math.floor(time_in_seconds) : Math.ceil(time_in_seconds);
b. If you want to just have the mathematical definition of integer division to hold, just take the floor. (Python's integer division does this).
time_in_seconds_int = Math.floor(time_in_seconds);
If you want only seconds as a whole number without the decimals representing milliseconds still attached, use this:
var seconds = Math.floor(new Date() / 1000);
You can create a Date object (which will have the current time in it) and then call getTime() to get the ms since epoch.
var ms = new Date().getTime();
If you want seconds, then divide it by 1000:
var sec = new Date().getTime() / 1000;
My preferred way:
var msEpoch = (+new Date());
var sEpoch = (+new Date()) / 1000;
For more information on the + jump down the rabbit hole.
The most simple version:
Math.floor(Date.now() / 1000)
EPOCH means time from 01 January 1970
var date = new Date();
Following line will return the number of milliseconds from 01 Jaunary 1970
var ms = date.getTime();
Following line will convert milliseconds to seconds
var seconds = Math.floor(ms/1000);
console.log("Seconds since epoch =",seconds);
In chrome you can open the console with F12 and test the following code:
var date = new Date().getTime()
console.debug('date: ' + date);
if (Date.now() < date)
console.debug('ko');
else
console.debug('ok');
https://www.eovao.com/en/a/javascript%20date/1/how-to-obtain-current-date-in-milliseconds-by-javascript-(epoch)

Categories

Resources