SoFunction
Updated on 2025-03-10

3 ways to convert timestamps into YYYY-MM-DD HH:mm:ss in js

Method 1: dayjs (most recommended)

npm install dayjs
# oryarn add dayjs
const dayjs = require('dayjs');
 
// Suppose you have a timestampconst timestamp = 1650000000000; // Sample timestamp 
// Convert timestamps using dayjsconst formattedDate = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
 
(formattedDate); // Output the converted date and time

Method 2:

npm install moment
// Introduce the libraryconst moment = require('moment');
 
// Suppose you have a timestampconst timestamp = 1609459200000; // For example: Time stamp at 00:00:00 on January 1, 2021 
// Use the conversion timestamp to YYYYMMDD HH:mm:ss formatconst formattedDate = moment(timestamp).format('YYYYMMDD HH:mm:ss');
 
(formattedDate); // Output: 20210101 00:00:00

Method 3: Native js (not recommended)

function timestampToYMDHMS(timestamp) {
  const date = new Date(timestamp);
  const year = ();
  const month = ('0' + (() + 1)).slice(-2); // Month starts from 0  const day = ('0' + ()).slice(-2);
  const hours = ('0' + ()).slice(-2);
  const minutes = ('0' + ()).slice(-2);
  const seconds = ('0' + ()).slice(-2);
  return `${year}${month}${day} ${hours}:${minutes}:${seconds}`;
}
 
// Example:const timestamp = (); // Or any other timestampconst formattedDate = timestampToYMDHMS(timestamp);
(formattedDate); // The output format is as:20230310 12:34:56

Attachment: Determine whether the date has passed

The code is as follows (example):

var timestampNow = (new Date());//Get the current time stampif(timestamp-timestampNow<0){//Judge according to the difference of the timestamp  ({
    isPast:true
  })
}else{
  ({
    isPast:false
  })
}

Summarize

This is the article about the three implementation methods of converting timestamps into YYYY-MM-DD in js. This is all about this. For more related js timestamp conversion YYYY-MM-DD HH:mm:ss content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!