How to get current timestamp in JavaScript?

How to get current timestamp in JavaScript?

To get the current timestamp in JavaScript, you can use the Date.now() method. This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Here is an example of how to use it:

const timestamp = Date.now();
console.log(timestamp); // prints the current timestamp

Alternatively, you can also create a new Date object and use the getTime() method to get the timestamp. This method returns the same value as Date.now(). Here is an example:

const date = new Date();
const timestamp = date.getTime();
console.log(timestamp); // prints the current timestamp

Note that the timestamp value returned by these methods is a large number representing the number of milliseconds since the epoch. To format the timestamp as a date and time string, you can use the toString() method or a library like moment.js.

Get current timestamp using Moment.js

Here is an example of how to use moment.js to get the current timestamp and format it as a date and time string in UTC:

const moment = require('moment');

const timestamp = moment().utc().format();
console.log(timestamp); // prints the current timestamp in UTC as a string

Note that this example uses Node.js syntax to require the moment.js library. In a browser, you would need to include the moment.js library using a <script> tag.

Overall, there are many ways to get the current timestamp in JavaScript, and which method you use will depend on your specific requirements and preferences. The Date object and its methods are built into JavaScript and are a good choice for simple use cases, while moment.js and other libraries offer more advanced features and formatting options.

Timestamp in UTC (Coordinated Universal Time)

If you need the timestamp in Coordinated Universal Time (UTC), you can create a new Date object using the Date.UTC() method, which takes the year, month, day, hour, minute, second, and milliseconds as arguments. This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Here is an example of how to use it:

const date = new Date();
const timestamp = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
console.log(timestamp); // prints the current timestamp in UTC

You can also use the getTime() method on a Date object created using the Date.UTC() method to get the timestamp in UTC. Here is an example:

const date = new Date(Date.UTC());
const timestamp = date.getTime();
console.log(timestamp); // prints the current timestamp in UTC

Note that the timestamp value returned by these methods is a large number representing the number of milliseconds since the epoch. To format the timestamp as a date and time string in UTC, you can use the toUTCString() method or a library like moment.js.