How can I get seconds since epoch in Javascript? - 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)

Related

Subtracting 100s of minutes accurately with Javascript

If I have two values, each representing a date such as YYYYMMDDHHMM (YearMonthDayHourMinute) like:
202012141800
202012141614
What I was trying to convey in the question is that this gives me 186 minutes, but this isn't accurate, however, since the last two digits will never be larger than 59 given 60 minutes in an hour. The 100 in 186 comes from hours 18 (6pm) and 16 (4pm).
How can I subtract these in Javascript to account for the extra 40 minutes tacked on if the two timestamps are more than an hour apart?
I have this, but it's not that efficient since I'd need to know the maximum number of hours two timestamps could be apart:
var end_time = $('#the-agenda li.current time').data('end-time'),
time_now = current_display_number,
timer_duration = end_time - time_now;
if (timer_duration > 200) {
// if more than 2 hours, subtract 80 minutes
timer_duration = timer_duration - 80;
}
else if (timer_duration > 100) {
// if more than 1 hour, subtract 40 minutes
timer_duration = timer_duration - 40;
}
I feel like the answer may somehow be in this question's answer, but I am not sure how to apply that parseInt to this situation.
You wouldn't use parseInt. You would use Date.parse, except that the string has to be in a predefined format. Without using a specialized library, you'll have to parse the parts yourself and then create a new Date with the parts. Fortunately though the incoming strings seem straightforward to parse. Do something like this:
let startTimeStr = '202012141614';
let endTimeStr = '202012141800';
let asDateTime = (d) => new Date(
d.substring(0,4),
d.substring(4,6) - 1,
d.substring(6,8),
d.substring(8,10),
d.substring(10,12)
)
let startTime = asDateTime(startTimeStr);
let endTime = asDateTime(endTimeStr);
let result = (endTime - startTime) / 60000;
console.log(result);
// Different in milliseconds
const difference = (new Date('2020-12-14T18:00:00')) - (new Date('2020-12-14T16:14:00'));
const inMinutes = Math.floor(difference / 60000);
You need to convert the string formats to a date object to get accurate date info.

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

Get the correct local time

I need to get the local time. I created this script but, for example, in italy ( where I live ), the alert shows 7 instead of 9. Why ?
var time = new Date().getTime();
var seconds = time / 1000;
seconds = seconds % 86400;
hours = parseInt(seconds / 3600);
alert(hours);
Because getTime returns the timestamp in milliseconds. And the timestamp is timezone independent. Use getTimezoneOffset() to get the offset in minutes from UTC, and add it.
new Date().getHours() will give you the local time, no adjustment needed.
new Date().getTimezoneOffset() will give you the number of minutes from UTC in the users's locale, should you need to offset an absolute time.
Note that UNIX timestamps measure the number of seconds since the UNIX epoch as if every day was exactly 3600 * 24 seconds. That allows you to get the time on most days with divisions and modulos, but if your timestamp is earlier than the latest leap second, and you try to do some simple maths with it, the result will not be accurate.
DEMO : http://jsfiddle.net/yk3wkcr8/
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
alert(h);
alert(m);
alert(s);
If you want an example, try this: Fiddle
It uses full array with seconds, minutes, hours, date, day and year.
BTW you can use getHours(); followed by the others.
var d = new Date(),
hours = d.getHours(),
hour = (hours - 12),
year = d.getFullYear(),
second = d.getSeconds(),
minute = d.getMinutes();
alert (hour + ":" + minute + ":" + second);
etc, etc.
You can try this:
new Date().toLocaleString()
it will give you something like:
"4/16/2015, 9:14:53 AM"
And if you need to obtain only the time stamp then you can split the resulting string into an array and get the second item from the array:
new Date().toLocaleString().split(',')[1]
If you need only the hours this is the way:
new Date().getHours()

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

Convert UNIX timestamp difference to minutes

I have 2 dates, that I convert to UNIX timestamp - start date and confirm date. I subtract one from another and get numbers like these:
-12643,
0,
3037,
1509,
-3069
Basically, what I need to do is to get the difference between the two dates in minutes, but I don't know how to convert those to minutes. The end output should be something like: -25, 13, 155
How did you get the original numbers? I believe the standard Unix timestamps are in seconds, so you should be able to divide by 60 to get minutes. However, Date.now() in JavaScript, for example, returns milliseconds, so you'd need to divide by 60,000.
Given two UNIX timestamps: a, b; you can calculate the difference between them in minutes like this:
var a = 1377005400000; //2013-07-20 15:30
var b = 1377783900000; //2013-07-29 15:45
var dateA = new Date(a);
var dateB = new Date(b);
var dayRelativeDifference = dateB.getHours()*60 + dateB.getMinutes()
- dateA.getHours()*60 - dateA.getMinutes();
// dayRelativeDifference will be 15
var absoluteDifference = (b-a)/60
// absoluteDifference will be 12975000
Also have a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
You just need to divide by 60. You already have the difference between the two timestamps, so none of the Date overhead above is necessary:
var diffs = new Array(-12643, 0, 3037, 1509, -3069);
for (var i = 0; i < diffs.length; i++)
document.write(diffs[i] % 60);

Categories

Resources