How to Convert Date to Timestamp in JavaScript

    Method 1: Using the Date.prototype.getTime() method

    To convert a date to a timestamp in JavaScript, you can use the Date.prototype.getTime() method. The method returns the number of milliseconds since the Unix epoch (January 1, 1970 00:00:00 UTC), but Unix timestamps are typically represented in seconds. To get the Unix timestamp in seconds, divide the result by 1000.

    Example

    // Create a Date object for the current date and time
    const date = new Date();
    
    // Convert the Date object to a Unix timestamp (in seconds)
    const timestamp = Math.floor(date.getTime() / 1000);
    
    console.log(timestamp);

    Output

    1680875058

    You can see that we got the timestamp from a date.

    Method 2: Using the Date.parse() method

    The Date.parse() is a built-in JavaScript function that returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. The date is obtained in string data types by default in Javascript. This can be converted into a timestamp using the Date.parse() method.

    Syntax

    Date.parse(date String)

    Parameters

    The date.parse() function takes a date argument, a string representation of a simplification of the ISO 8601.

    Return value

    The date.parse() method returns a number representing the milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC.

    Example

    const toTimeStamp = (strDate) => { 
     const dt = Date.parse(strDate); 
     return dt / 1000; 
    } 
    console.log(toTimeStamp('02/02/2022 23:31:30'));

    Output

    1643824890

    Explanation

    The toTimeStamp() is a user-defined function. So the user is free to use any name for the function. Likewise, the strDate() is a user-defined variable, so the user is free to choose the name of this variable too.

    The Date.parse() is a necessary built-in function and cannot be altered with another name.

    We got 1643824890 in the output means that since January 1, 1970, 00:00:00 UTC, 1643824890 milliseconds had passed when the user got the timestamp.

    Method 3: Using the valueOf() function

    The valueOf() function is a built-in JavaScript method that returns the primitive value of the specified object. It can be used with objects such as Number, String, Boolean, and Date. When called on an object, the valueOf() method returns the primitive value representing the object.

    Example

    const date = new Date();
    const timestamp = Math.floor(date.valueOf() / 1000);
    
    console.log(timestamp);

    Output

    1680875220

    The Math.floor() function rounds down the result to the nearest integer, as Unix timestamps are generally represented as whole seconds.

    That’s all!

    Leave a Comment