How to convert seconds to HH:mm:ss in moment.js - javascript

How can I convert seconds to HH:mm:ss?
At the moment I am using the function below
render: function (data){
return new Date(data*1000).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");;
}
This works on chrome but in firefox for 12 seconds I get 01:00:12
I would like to use moment.js for cross browser compatibility
I tried this but does not work
render: function (data){
return moment(data).format('HH:mm:ss');
}
What am I doing wrong?
EDIT
I managed to find a solution without moment.js which is as follow
return (new Date(data * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
Still curious on how I can do it in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:
const secs = 456;
const formatted = moment.utc(secs*1000).format('HH:mm:ss');
document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
for (var i=60;i<=60*60*5;i++) {
document.write(hhmmss(i)+'<br/>');
}
/*
function show(s) {
var d = new Date();
var d1 = new Date(d.getTime()+s*1000);
var hms = hhmmss(s);
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}
*/

You can use moment-duration-format plugin:
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
See also this Fiddle
Upd: To avoid trimming for values less than 60-sec use { trim: false }:
var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"

var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();

My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example.
And just use the 'formattedSeconds' where you need.

In a better way to utiliza moments.js; you can convert the number of seconds to human-readable words like ( a few seconds, 2 minutes, an hour).
Example below should convert 30 seconds to "a few seconds"
moment.duration({"seconds": 30}).humanize()
Other useful features: "minutes", "hours"

The above examples may work for someone but none did for me, so I figure out a much simpler approach
var formatted = moment.utc(seconds*1000).format("mm:ss");
console.log(formatted);

Until 24 hrs.
As Duration.format is deprecated, with moment#2.23.0
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');

How to correctly use moment.js durations?
|
Use moment.duration() in codes
First, you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

To display number of days along with hours, mins and seconds, you can do something like this:
const totalSec = 126102;
const remainingMillies= (totalSec % 86400) * 1000;
const formatted = `${Math.floor(totalSec / 86400)} day(s) and ${moment.utc(remainingMillies).format('hh:mm:ss')}`;
console.log(formatted );
will output :
1 day(s) and 11:01:42

In 2022 no need for any new plugin just do this
Literally all you need in 2022 prints out duration in hh:mm:ss from two different date strings
<Moment format='hh:mm:ss' duration={startTime} date={endTime} />

I think there's no need to use 3rd part libray/pluggin to get this task done
when using momentJS version 2.29.4 :
private getFormatedDuration(start: Date, end: Date): string {
// parse 'normal' Date values to momentJS values
const startDate = moment(start);
const endDate = moment(end);
// calculate and convert to momentJS duration
const duration = moment.duration(endDate.diff(startDate));
// retrieve wanted values from duration
const hours = duration.asHours().toString().split('.')[0];
const minutes = duration.minutes();
// voilà ! without using any 3rd library ..
return `${hours} h ${minutes} min`;
}
supports also 24h format
PS : you can test and calculate by yourself using a 'decimal to time' calculator at CalculatorSoup

Related

Moment UTC time how to convert to seconds [duplicate]

I want a single number that represents the current date and time, like a Unix timestamp.
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call Date.now:
Date.now()
Alternatively, use the unary operator + to call Date.prototype.valueOf:
+ new Date()
Alternatively, call valueOf directly:
new Date().valueOf()
To support IE8 and earlier (see compatibility table), create a shim for Date.now:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
Alternatively, call getTime directly:
new Date().getTime()
Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Math.floor(Date.now() / 1000)
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Date.now() / 1000 | 0
Timestamp in milliseconds (higher resolution)
Use performance.now:
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time
Math.floor() solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now() working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you need to remember this for dates after 2038:
Bitwise operations will cause usage of 32 Bit Integers instead of 64 Bit Floating Point.
You will need to properly use it as:
Math.floor(Date.now() / 1000)
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
const relativeTime = (() => {
const start = Date.now();
return () => Date.now() - start;
})();
In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version, consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0 does:
By providing |, you tell the interpreter to do a binary OR operation.
Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000 into an integer.
During that conversion, decimals are removed, resulting in a similar result to what using Math.floor() would output.
Be warned though: it will convert a 64 bit double to a 32 bit integer.
This will result in information loss when dealing with huge numbers.
Timestamps will break after 2038 due to 32 bit integer overflow unless Javascript moves to 64 Bit Integers in Strict Mode.
For further information about Date.now follow this link: Date.now() # MDN
var time = Date.now || function() {
return +new Date;
};
time();
var timestamp = Number(new Date()); // current time as number
In addition to the other options, if you want a dateformat ISO, you can get it directly
console.log(new Date().toISOString());
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime() expression)
REF: http://api.jquery.com/jQuery.now/
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since
1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now(); not works and you need to use:
new Date().getTime();
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
Performance
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Conclusions
Solution Date.now() (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
Solution performance.now() (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
Solutions C,D,F are quite slow on all browsers
Details
Results for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
This snippet only presents code used in external benchmark
Just to add up, here's a function to return a timestamp string in Javascript.
Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
The Date.getTime() method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor if necessary:
(new Date).getTime() / 1000
The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.
Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function.
It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;
console.log(ts);
I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
For a timestamp with microsecond resolution, there's performance.now:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
You can only use
var timestamp = new Date().getTime();
console.log(timestamp);
to get the current timestamp. No need to do anything extra.
// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)
// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720
// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087
// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377 where 245521377 is the timestamp generated by hrtime().
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
For lodash and underscore users, use _.now.
var timestamp = _.now(); // in milliseconds
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
MDN Documentation on Date.now
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();

How to get current date without time?

I'm trying to get the current date without the time and store it in a variable, within JavaScript. It needs to be without time as I'm converting it to an epoch date, with which I will use to measure the past 24 hours (if date is within 24 hours then it will be displayed). The problem is that with the added time, it doesn't match as within the last 24 hours.
e.g. it returns the date as the following when converted to epoch: 1408704590485
I want it to be like 1408662000000
I'm not to sure how to do this.
Code - How the current days epoch date is currently being stored -
var epochLoggingFrom;
var epochLoggingTo;
$(document).ready(function () {
epochLoggingFrom = dateToEpoch(new Date());
epochLoggingTo = dateToEpoch(new Date());
}
dateToEpoch function -
function dateToEpoch(thedate) {
return thedate.getTime();
}
Try this:
function dateToEpoch(thedate) {
var time = thedate.getTime();
return time - (time % 86400000);
}
or this:
function dateToEpoch2(thedate) {
return thedate.setHours(0,0,0,0);
}
Example : http://jsfiddle.net/chns490n/1/
Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
or use this:
dateToEpoch(new Date().toLocaleDateString())
I tried using javascript. this method returns the current date in "DD/MM/YYYY" format.
getCurrentDate() {
const t = new Date();
const date = ('0' + t.getDate()).slice(-2);
const month = ('0' + (t.getMonth() + 1)).slice(-2);
const year = t.getFullYear();
return `${date}/${month}/${year}`;
}

Javascript: how to add n minutes to unix timestamp

I have a unix timestamp: 1368435600. And a duration in minutes: 75 for example.
Using javascript I need to:
Convert the timestamp to a string format hours:mins (09:00)
Add n minutes to the timestamp: timestamp + 75mins
I tried the moment.js library:
end_time = moment(start_time).add('m', booking_service_duration);
booking_service_duration was 75 but it added an hour. I'd also rather not have to use another js library
To add 75 minutes, just multiply by 60 to get the number of seconds, and add that to the timestamp:
timestamp += 75 * 60
To convert to hours:mins you will have to do a bit more math:
var hours = Math.floor(timestamp/60/60),
mins = Math.floor((timestamp - hours * 60 * 60) / 60),
output = hours%24+":"+mins;
Unix time is the number of seconds that have elapsed since 1 January 1970 UTC.
To move that time forward you simply add the number of seconds.
So once you have the minutes, the new timestamp is oldTime + 60*minutes
For the conversion look up parsing libraries, there is code out there for this, do some research.
So you want to convert a timestamp you have, timestamp, to locale time string after adding some time interval, specifically minutes, to it.
Whether you have a kind of date-time string or a kind of epoch mili/seconds, just create a Date object:
const date = new Date(timestamp);
Keep in mind since what you need to do require to add/substract some numbers (your case: minutes) to another number, not some date object or some date-time string, and that number is the epoch mili/secods of your date. So, always you will need the number representation of your date in mili/seconds. JavaScript Date.prototype.getTime() does return epoch miliseconds of your date. Use it:
const miliseconds = date.getTime();
Add as many as miliseconds to it:
const newMiliseconds = miliseconds + (75 * 60 * 1000);
After that, as you said you need a date-time string, well a portion of it; locale time string, you will need to go all the way back; from numbers to date object and to a date-time string:
const newDate = new Date(newMiliseconds);
const newTimestamp = newDate.toString();
Or instead of getting the whole string of it, use the following specialized method to get the format/portion of the string representation of the date object that you like directly:
const newTimestamp = newDate.toLocaleTimeString(); // "12:41:43"
Finally, all you have to do is to just strip the last semicolon and seconds to get hours:minutes format:
const newHoursMins = newTimestamp.slice(0, -3);
Better make a function of it:
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
I left the final formatting out here. You can use this for substraction as well by pasing a negative second argument. Note the seconds argument is in miliseconds and unix timestamp varies and might given to you as seconds instead, in which case you will need to convert it to miliseconds or change the above funciton definition.
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
console.log("new Date(1368435600*1000).toLocaleTimeString(): ", new Date(1368435600*1000).toLocaleTimeString())
console.log("timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleString): ", timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleTimeString))
Apart from what you need, for last parameter, toStringFunc, your options vary and encompasses all related Date methods, the are on Date.prototype:
toString
toDateString
toTimeString
toLocaleString
toLocaleDateString
toLocaleTimeString
toIsoString
toUTCString
toGMTString
toJSON

Countdown timer with cookies

I know there have been a lot of topics like this but I just have problem to which I couldn't find the answer.
My script is:
window.onload = function(){
// 200 seconds countdown
var countdown = 14400;
//current timestamp
var now = Date.parse(new Date());
//ready should be stored in your cookie
if ( !document.cookie )
{
document.cookie = Date.parse(new Date (now + countdown * 1000)); // * 1000 to get ms
}
//every 1000 ms
setInterval(function()
{
var diff = ( document.cookie - Date.parse(new Date()) );
if ( diff > 0 )
{
var message = diff/1000 + " seconds left";
}
else
{
var message = "finished";
}
document.body.innerHTML = message;
},1000);
}
I want to make countdown timer which tells user time how much left depending on his cookie value. So far I managed to calculate difference between two values but I don't know how to make format like, let's say, "dd/mm/yy hh:mm:ss" from difference timestamp (diff). Is it possible at all?
What you want is a function that converts difference in (mili)seconds to something like
5d 4h 3m 2s
If you don't mind having a large number of days for times periods > a few months, then you could use something like this:
function human_time_difference(diff) {
var s = diff % 60; diff = Math.floor(diff / 60);
var min = diff % 60; diff = Math.floor(diff / 60);
var hr = diff % 24; diff = Math.floor(diff / 24);
var days = diff;
return days + 'd ' + hr + 'h ' + min + 'm ' + s + 's';
}
If you have the difference in miliseconds, you'll need to pass the that number divided by 1000. You can also use Math.round to get rid of fractions, but you could just as well leave them on if you want that information displayed.
Getting months and years is a little trickier for a couple of reasons:
The number of days in a month varies.
When you're going from the middle of one month to the middle of the next, the time span doesn't cover any whole months, even if the number of days > 31 (e.g. How many months are there between the 2nd of June and the 30th of July??).
If you really want the number of months between two times, the number of seconds between them is not enough. You have to use calendar logic, which requires passing in the start and end date + time.
PS: When you post a question, avoid irrelevant details. For example, your question has nothing to do with cookies, setInterval, or onload handlers. The only part that you don't know is how to convert (mili)seconds to days, hours, etc. It might be helpful to supply some background on why you're trying to do something, but if it's not essential to understand the basic question, put it at the end so that people don't have to wade through it before getting to the essential part. The same advice applies to your title; make sure it's relevant by excluding irrelevant details (e.g. cookies and counting down).
JavaScript doesn't have any built in date formatting methods like you might expect if you've done any PHP. Instead, you have to build the string manually. However, there are a number of getter methods that will be useful to this end. See 10 ways to format time and date using JavaScript.
Also, just so you know. Date.parse doesn't return the millisecond portion of the time stamp (it rounds down). If you need the milliseconds, you can do either of the following
var d = new Date();
var timestamp_ms = Date.parse(d) + d.getMilliseconds();
or just
var timestamp_ms = +d;
I do not understand why you check the cookie by if ( !document.cookie ) But it doesnot work on my browser so I modified it into if ( document.cookie )
Try toString function and other. Look them up in javascript Date object reference. For example,
var t = new Date;
t.setTime(diff);
var message = t.toTimeString() + " seconds left";
This will print 11:59:58 seconds left on my browser.

How do I get a timestamp in JavaScript?

I want a single number that represents the current date and time, like a Unix timestamp.
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call Date.now:
Date.now()
Alternatively, use the unary operator + to call Date.prototype.valueOf:
+ new Date()
Alternatively, call valueOf directly:
new Date().valueOf()
To support IE8 and earlier (see compatibility table), create a shim for Date.now:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
Alternatively, call getTime directly:
new Date().getTime()
Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Math.floor(Date.now() / 1000)
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Date.now() / 1000 | 0
Timestamp in milliseconds (higher resolution)
Use performance.now:
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time
Math.floor() solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now() working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you need to remember this for dates after 2038:
Bitwise operations will cause usage of 32 Bit Integers instead of 64 Bit Floating Point.
You will need to properly use it as:
Math.floor(Date.now() / 1000)
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
const relativeTime = (() => {
const start = Date.now();
return () => Date.now() - start;
})();
In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version, consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0 does:
By providing |, you tell the interpreter to do a binary OR operation.
Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000 into an integer.
During that conversion, decimals are removed, resulting in a similar result to what using Math.floor() would output.
Be warned though: it will convert a 64 bit double to a 32 bit integer.
This will result in information loss when dealing with huge numbers.
Timestamps will break after 2038 due to 32 bit integer overflow unless Javascript moves to 64 Bit Integers in Strict Mode.
For further information about Date.now follow this link: Date.now() # MDN
var time = Date.now || function() {
return +new Date;
};
time();
var timestamp = Number(new Date()); // current time as number
In addition to the other options, if you want a dateformat ISO, you can get it directly
console.log(new Date().toISOString());
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime() expression)
REF: http://api.jquery.com/jQuery.now/
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since
1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now(); not works and you need to use:
new Date().getTime();
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
Performance
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Conclusions
Solution Date.now() (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
Solution performance.now() (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
Solutions C,D,F are quite slow on all browsers
Details
Results for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
This snippet only presents code used in external benchmark
Just to add up, here's a function to return a timestamp string in Javascript.
Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
The Date.getTime() method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor if necessary:
(new Date).getTime() / 1000
The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.
Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function.
It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;
console.log(ts);
I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
For a timestamp with microsecond resolution, there's performance.now:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
You can only use
var timestamp = new Date().getTime();
console.log(timestamp);
to get the current timestamp. No need to do anything extra.
// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)
// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720
// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087
// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377 where 245521377 is the timestamp generated by hrtime().
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
For lodash and underscore users, use _.now.
var timestamp = _.now(); // in milliseconds
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
MDN Documentation on Date.now
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();

Categories