Languages
[Edit]
EN

TypeScript - format current date to yyyy-mm-dd (Iso 8601)

0 points
Created by:
James-Z
767

In this article, we would like to show you how to format the current date to yyyy-mm-dd using TypeScript.

Date in yyyy-mm-dd format - TypeScript
Date in yyyy-mm-dd format - TypeScript

Quick solution:

// output format: yyyy-mm-dd
const getDateInFormat_yyyy_mm_dd = (): string => {
  const toString = (date: number, padLength: number) => {
    return date.toString().padStart(padLength, '0');
  };

  const date = new Date();

  const dateTimeNow = toString(date.getFullYear(), 4) + '-' + toString(date.getMonth() + 1, 2) + '-' + toString(date.getHours(), 2);
  return dateTimeNow;
};

console.log(getDateInFormat_yyyy_mm_dd()); // 2022-03-13

Output:

2022-03-13

 

Practical examples

Example 1

// output format: yyyy-mm-dd
const getDateInISO_8601 = (): string => {
  const date = new Date();
  const year = '' + date.getFullYear();
  let month = '' + (date.getMonth() + 1);
  let day = '' + date.getDate();

  if (month.length < 2) {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }
  return year + '-' + month + '-' + day;
};

console.log(getDateInISO_8601()); // 2022-03-14

Output:

2022-03-14

Example 2

const getIso8601Date = (date?: Date): string => {
  if (date == null) {
    date = new Date();
  }

  const year = String(date.getFullYear());
  let month = String(date.getMonth() + 1);
  let day = String(date.getDate());

  if (month.length < 2) {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }

  return year + '-' + month + '-' + day;
};


// Usage example:

const date = new Date(2021, 5, 13); // 2021-05-13 - e.g. recived from server

console.log(getIso8601Date(date)); // 2021-06-13
console.log(getIso8601Date()); // 2022-03-14

Output:

2021-06-13
2022-03-14
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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