date.toLocaleDateString 不是函数

问题描述 投票:0回答:6

有返回错误的简单函数:

错误:date.toLocaleDateString 不是函数

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

函数定义:

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

函数接收

Date
对象作为输入,但即使使用
Date
显式转换为
Date.parse()
也无济于事。使用 Node.js 8.x。有什么解决办法吗?

P.S. 问题是由 BotBuilder 架构引起的。

javascript node.js string date botframework
6个回答
40
投票

你可以使用

new Date(date).toLocaleDateString();

39
投票

Date.parse
返回一个数字。您正在寻找
new Date
。或者,如果
time
已经是 Date 实例,只需使用
time.toLocaleDateString()
(并确保它确实存在于每次调用该函数时)!

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

5
投票

在 React 应用程序中遇到此错误,如下解决:

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

0
投票

您很可能会因

NaN
通话而得到
Date.parse(time)
。 如果您认为时间参数应该有效,请查看关于 Date.parse 的 MDN 文章,了解它接受的输入字符串类型。

您可能想要修改 return 语句,以便它检查失败的解析,而不仅仅是未定义,例如:

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

0
投票

我已经使用下面的代码解决了这个错误;

使用 toLocaleString 代替 date.toLocaleDateString

//分别为月、日、年

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

-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; 
 }
© www.soinside.com 2019 - 2024. All rights reserved.