Home > Mobile >  Passing options argument to The toLocaleString() method removes the time portion from the output
Passing options argument to The toLocaleString() method removes the time portion from the output

Time:02-19

I want to convert a UTC timestamp to mm/dd/yyyy hh:mm:ss format in Javascript.

timestamp = '1645199199.241098'


const d1 = new Date(parseInt(timestamp) * 1000)
        .toLocaleString("en-US",
            {
             hour12:false,
             timeZone: 'America/Chicago',
});

console.log(d1)

This code above does not give me two digit months and days. Setting the options for 2-digit month and day gives me the correct date format but removes the time from the output all together.

timestamp = '1645199199.241098'

const d2 = new Date(parseInt(timestamp) * 1000)
        .toLocaleString("en-US",
            {hour12:false,
             timeZone: 'America/Chicago',
             year: 'numeric',
             month: '2-digit',
             day: '2-digit'
});

console.log(d2);

How do I retain the time and get the date in the desired format in my output?

CodePudding user response:

You can add the remaining options for hour, minute, and second:

const timestamp = '1645199199.241098';

const d2 = new Date(parseInt(timestamp) * 1000)
  .toLocaleString("en-US", {
    hour12: false,
    timeZone: 'America/Chicago',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

console.log(d2);

Documentation regarding available options and value format values:

https://tc39.es/ecma402/#sec-datetimeformat-abstracts

CodePudding user response:

When you start specifying what parts you want to have in the string, the rest of them default to being absent. If you want the time, you need to tell it that:

const timestamp = "1645199199.241098"
const d2 = new Date(parseInt(timestamp) * 1000)
    .toLocaleString("en-US", {
        hour12: false,
        timeZone: "America/Chicago",
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "numeric",    // ***
        minute: "numeric",  // ***
        second: "numeric",  // ***
    });
console.log(d2);

  • Related