Home > OS >  JavaScript date time conversion not returning the value
JavaScript date time conversion not returning the value

Time:12-28

I want to convert timestamp (in millis) into date and show it into a table cell. Below is the code I wrote for conversion.

var start = match.startAt;
    console.log(start);
    var startTime = new Date(start);
    var t = startTime.toLocaleDateString

and I am displaying it as

<td>{t}</td>

In console, it is just showing "ƒ toLocaleDateString() { [native code] }" I couldn't figured out why it is not displaying anything. Can someone help to resolve the issue.

CodePudding user response:

it should be var t = startTime.toLocaleDateString() not var t = startTime.toLocaleDateString because toLocaleDateString is a function

CodePudding user response:

You need to call the toLocaleDateString method by adding parentheses after it, like this:

var start = match.startAt;
console.log(start);
var startTime = new Date(start);
var t = startTime.toLocaleDateString();

The t variable should be a reference to the toLocaleDateString function, which makes the right approach to do it. However, you need to call the function itself to get the date string.

As follows, you will have the applied fix:

var start = match.startAt;
console.log(start);
var startTime = new Date(start);
var t = startTime.toLocaleDateString();

Where it will display the date in the table cell now by doing:

<td>{t}</td>

Moreover, you can also specify the language and formatting options for the date string by passing them as arguments to toLocaleDateString like this:

var t = startTime.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

This would display the date in the US English format. Additionally, you will have the display of the weekday, full name and numeric day of the month, as well as numeric year.

CodePudding user response:

Should invoke the function.

var start = match.startAt;
console.log(start);
var startTime = new Date(start);
var t = startTime.toLocaleDateString // wrong
// var t = startTime.toLocaleDateString(); // correct
  • Related