49

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.

Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101
  • 4
    `Date.parse` returns a number. You are looking for `new Date`. Or, if `time` already is a Date instance, just use `time.toLocaleDateString()`! – Bergi Aug 17 '17 at 00:43
  • What is the value of *time*? – RobG Aug 17 '17 at 00:46
  • @Bergi thanks, this works. Strange when values was inside function - their was `Date` type with `Date()` constructor, outside - become strings: probably bot framework on waterfall flow functions assignment loses type and need to convert explicitly. You may move Your comment to answers. Thanks! – Aleksey Kontsevich Aug 17 '17 at 00:57

5 Answers5

40

You can use

new Date(date).toLocaleDateString();
Viplav Soni
  • 1,489
  • 13
  • 18
39

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() : "";
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
4

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

{ (item.created instanceof Date) ? item.created.toLocaleDateString() : new Date(item.created).toLocaleDateString() }
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • You can directly use `new Date(date).toLocaleDateString();`, On your code a if condition will take time to excecute. – Viplav Soni May 06 '21 at 11:41
0

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();
}
Matt McMahon
  • 655
  • 5
  • 5
-4
 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; 
 }