Languages
[Edit]
EN

JavaScript - custom date & time format

6 points
Created by:
Dirask JS Member
3610

In this article, we would like to show you how to use the custom format date and time in JavaScript.

yyyy.MM.dd_HH.mm.ss format for DateTime - JavaScript
yyyy.MM.dd_HH.mm.ss format for DateTime - JavaScript

 

To do this, we will use the padStart function, which pads the given string with another string until it is the desired length.

Check out the example below to see how it works:

// ONLINE-RUNNER:browser;

const renderNumber = (value, size) => {
	const text = String(value);
  	return text.padStart(size, '0');
};

const formatDate = (date = new Date()) => {
    const year    = renderNumber(date.getFullYear(),  4);
    const month   = renderNumber(date.getMonth() + 1, 2);
    const day     = renderNumber(date.getDate(),      2);
    const hours   = renderNumber(date.getHours(),     2);
    const minutes = renderNumber(date.getMinutes(),   2);
    const seconds = renderNumber(date.getSeconds(),   2);
    return `${year}.${month}.${day}_${hours}.${minutes}.${seconds}`;
};

// Usage example:

const date = new Date(2000, 05, 15, 12, 30, 20);

console.log(formatDate());     // 2021.03.23_18.37.25
console.log(formatDate(date)); // 2000.06.15_12.30.20

Note: 

The padStart function is a relatively new feature (ES2017) and may not be compatible with all browsers, it is worth to protect against it and add a polyfill to our web page or paste just following code:

/**
 * String.padStart()
 * version 1.0.1
 * Feature	        Chrome  Firefox Internet Explorer   Opera	Safari	Edge
 * Basic support	57   	51      (No)	            44   	10      15
 * -------------------------------------------------------------------------------
 */
if (!String.prototype.padStart) {
  String.prototype.padStart = function padStart(targetLength, padString) {
    targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
    padString = String(typeof padString !== 'undefined' ? padString : ' ');
    if (this.length > targetLength) {
      return String(this);
    } else {
      targetLength = targetLength - this.length;
      if (targetLength > padString.length) {
        padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
      }
      return padString.slice(0, targetLength) + String(this);
    }
  };
}

References

  1. padStart - MDN Docs
  2. JavaScript - how to get only current date?

JavaScript - Date & Time

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join