In everyday web development, dealing with dates and times is an unavoidable task. JavaScript, as one of the core languages for web development, provides a range of methods to handle time, especially timestamps. This article will introduce methods to obtain timestamps and various ways to convert JavaScript timestamps, as well as share some practical tips.

Methods to Obtain Timestamps

Here are five methods to get the current timestamp in JavaScript:

Using the Date.now() Method

This is the most direct method to obtain the current timestamp. It returns the milliseconds representation at the time of calling.

console.log(Date.now()); // Output example: 1642471441587

Converting a Time String with Date.parse()

This method parses a string representing a date and returns the timestamp of that date. However, it should be noted that it converts the milliseconds value to 000.

console.log(Date.parse(new Date())); // Output example: 1642471535000
console.log(Date.parse("2022/1/18 10:05")); // Output example: 1642471500000

The valueOf() Method

This method returns the primitive value of a Date object, that is, the timestamp.

console.log((new Date()).valueOf()); // Output example: 1642471624512

The getTime() Method

This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC for the date object.

console.log(new Date().getTime()); // Output example: 1642471711588

Converting to a Number Type

By using the Number constructor on a Date object, you can get the timestamp.

console.log(Number(new Date())); // Output example: 1642471746435

Converting Timestamp to Date

After obtaining the timestamp, we often need to convert it into a readable date format. Here are two common conversion methods:

Converting to a Local Time String

Using the toLocaleString() method, you can obtain a string in the local time format.

function getLocalTime(n) {
    return new Date(parseInt(n)).toLocaleString().replace(/:\d{1,2}$/, ' ');
}
console.log(getLocalTime(1642471746435)); // Output example: '2022/1/18 10:09 AM'

Formatting into a Custom Format

You can create a date string in a custom format by concatenating the date components.

function customFormatDate(timestamp) {
    let date = new Date(timestamp),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds();
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
console.log(customFormatDate(1642471746435)); // Output example: '2022-1-18 10:09:06'