Home > Blockchain >  Get Date in Consistent Format
Get Date in Consistent Format

Time:12-31

I am having a function which return the date based on some condition (last 30 day).

const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
const startTime = start.toLocaleString().split(",")[0];
console.log(startTime)

In Mac OS,I am getting the output in dd/mm/yyyy format (which is the desired format).

But in Windows , I am getting the output in mm/dd/yyyy. How can I make it consistent irespective of platform. Desired format is dd/mm/yyy

CodePudding user response:

Use toLocaleDateString with locale (and optional options)

The en-GB locale seems what you want here

const options = {year: 'numeric', month: 'numeric', day: 'numeric' }; // default options

const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
console.log(start.toLocaleDateString('en-GB', options));

CodePudding user response:

Use toLocaleDateString with 'en-GB'

const start = new Date();
start.setDate(start.getDate() - 30)
const startTime = start.toLocaleDateString('en-GB');
console.log(startTime)

CodePudding user response:

function SetShortDateTime(d) {
  const monthList = [
    "01",
    "02",
    "03",
    "04",
    "05",
    "06",
    "07",
    "08",
    "09",
    "10",
    "11",
    "12"
  ];


  const yr = d.getFullYear();
  const mnt = monthList[d.getMonth()];
  const day = d.getDate() < 10 ? "0"   d.getDate() : d.getDate();

  return [day, mnt, yr].join("/");
}

console.log(SetShortDateTime(new Date(2021,11,9,10)))

  • Related