Related
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();
This question already has an answer here:
new Date() for a specific timezone in JavaScript
(1 answer)
Closed 5 years ago.
This seemed fairly trivial but I might be over-thinking it.
I would like to render my chat widget between 9AM(PST) and 5PM(PST) mon-fri
Using new Date() always puts time into the browsers time zone. Basically i need to instantiate a date in PST and check if between days and hours.
var d = new Date();
var day = d.getDay();
var hour = d.getHours();
if (day > 0 && day < 6 && hour > 9 && hour < 17) {
renderChatWidget($('#chat-widget')):
}
I think this is incorrect because it uses the browser time, so if its 9:30AM in London then PST time would be like 2am and it would still render the chat widget...
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
document.getElementById('title').innerHTML=(calcTime('California', '-7'));
<h1 id="title">Time Zone Example</h1>
This is from this post and I just turned it into a snippet to see it work. You can then use the modified (correct) date through your tests using the correct time zone.
You can use UTC time.
var current_time = new Date;
var utc_time = Date.UTC(
current_time.getUTCFullYear(),
current_time.getUTCMonth(),
current_time.getUTCDate() ,
current_time.getUTCHours(),
current_time.getUTCMinutes(),
current_time.getUTCSeconds(),
current_time.getUTCMilliseconds());
Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}
I'm looking for a way to shift the browser's Date to a specified one without freezing time. Let's pretend I have some function shiftDate() which does just that. The following outlines the behavior I'm seeking:
// Here's the current time.
new Date().getTime(); //=> 1391109350382
//
// Now let's call the function to shift/travel back in time and _immediately_
// check the time afterwards
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
//
// Now let's wait 1111 ms and then check the time again
new Date().getTime(); //=> 1388534401111
//
// Let's wait another 1111 ms
new Date().getTime(); //=> 1388534402222
//
// Let's shift/travel back in time once more
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
//
// Then wait 1111 ms again
new Date().getTime(); //=> 1388534401111
//
// And wait 1111 ms again
new Date().getTime(); //=> 1388534402222
Notice time keeps ticking after each shift. Most solutions that I've found entirely freeze time through a mock or stub of some sort. However, freezing time is not an appropriate solution: doing so disrupts other time-dependent features such as animations. Below is an example, which freezes time:
new Date().getTime(); //=> 1391109350382
var oldDate = Date;
Date = function() { return new oldDate('2014-01-01'); };
var testDate = new Date();
new Date().getTime(); //=> 1388534400000
// Wait 1111 ms, ten minutes, or an hour: time will never change
new Date().getTime(); //=> 1388534400000
Check out Momentjs for handy date and time manipulation.
http://momentjs.com/
// Let's shift/travel back in time once
shiftDate('2014-01-01');
new Date().getTime(); //=> 1388534400000
I'm not sure why you don't simply do new Date('2014-01-01').getTime(); in your custom, shifted logic?
However, you can get the desired behaviour with the following function:
function shiftDate(to) {
var realDate = Date;
Date = function frozenDate() {
Date = realDate;
return new Date(to);
};
}
When you call shiftDate, the next - and only the next - call to Date will yield a date from a confused timeline.
I dont think there is any way you can change the date objects internal time pointer (if you want to call it that) without going deep into the OS. I think you'd have to write your own little library, similar to this:
var myDate = function(dateStr){
var initTime = new Date().getTime()
var dateObj = new Date(dateStr);
var myDateTime = dateObj.getTime();
// subtract the init time from the time this method is called
// to get a difference, then add it to your "old" time to get
// the updated millisecond value
this.getTime = function(){
var currentTime = new Date().getTime();
var dif = currentTime - initTime;
return myDateTime + dif;
};
};
You could of course get fancy with the methods and implement all of the native Date object methods.
I've got it! The trick is to keep track of the time change within a new Date prototype. Here's a rough implementation:
function shiftDate(date) {
window.trueDate = window.trueDate || Date;
var trueStart = new trueDate().getTime();
var shiftedStart = new Date(date).getTime();
Date = function() {
var timeChange = new trueDate() - trueStart;
return new trueDate(shiftedStart + timeChange);
}
}
And here's a simple test:
shiftDate('2014-01-01')
testDate = new Date();
setInterval(function(){
console.log(new Date().toString());
}, 1000);
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();