Aleksey Kontsevich
Aleksey Kontsevich

Reputation: 4991

date.toLocaleDateString is not a function

Have simple function which returns an error:

ERROR: date.toLocaleDateString is not a function

TypeError: date.toLocaleDateString is not a function
    at FormatTime (../Src/rootdialog.js:87:58)

Function definition:

function FormatTime(time, prefix = "") {
    var date = Date.parse(time);
    return ((typeof time != "undefined") ? prefix + date.toLocaleDateString()  : "");
}

Function receives Date object as input however even explicit conversion to Date with Date.parse() does not help. Using Node.js 8.x. Any solution?

P.S. Issue was caused by BotBuilder architecture.

Upvotes: 56

Views: 104735

Answers (6)

Megha Thattaru
Megha Thattaru

Reputation: 1

I have solved this error by using the code below;

Instead of date.toLocaleDateString, use toLocaleString

// month, day, year respectively

const month = props.date.toLocaleString('en-US', {month:'long'});
const day = props.date.toLocaleString('en-US', {day:'2-digit'});
const year = props.date.getFullYear();

Upvotes: -1

Ogglas
Ogglas

Reputation: 69998

Got this error in a React app, solved it like this:

{ (item.created instanceof Date) ? item.created.toLocaleDateString() : new Date(item.created).toLocaleDateString() }

Upvotes: 6

Viplav Soni
Viplav Soni

Reputation: 1727

You can use

new Date(date).toLocaleDateString();

Upvotes: 54

RaVi R Pant
RaVi R Pant

Reputation: 1

 function(ng-model_Name,ng-model_Name) {
     var fromdate = new Date($scope.ng-model_Name.from.toLocaleDateString());
     var todate = new Date($scope.ng-model_Name.to.toLocaleDateString());
     return $scope.variable= asign; 
 }

Upvotes: -4

Bergi
Bergi

Reputation: 664548

Date.parse returns a number. You are looking for new Date. Or, if time already is a Date instance, just use time.toLocaleDateString() (and make sure it really is in every call to the function)!

function formatTime(time, prefix = "") {
    return typeof time == "object" ? prefix + time.toLocaleDateString() : "";
}

Upvotes: 40

Matt McMahon
Matt McMahon

Reputation: 655

You're most likely getting NaN as the result of your Date.parse(time) call. Check the MDN article on Date.parse for the types of input strings it accepts if you think your time argument should be valid.

You may want to modify your return statement so it's checking for failed parses instead of just undefined, e.g.:

function FormatTime(time, prefix = "") {
    var date = Date.parse(time); // returns NaN if it can't parse
    return Number.isNaN(date) ? "" : prefix + date.toLocaleDateString();
}

Upvotes: 0

Related Questions