将日期转换为文本

时间:2017-12-24 17:29:05

标签: javascript date text time

我正在尝试编写将日期转换为文本的代码,例如“上午8:00”,不知道我在哪里绊倒。 我正在使用http://labs.codecademy.com/#:workspace来测试此代码。

var today = new Date(); 

   function calculateMeridian(num){
    if (num < 12) {
        return "AM";
    } else if (num < 24) {
        return "PM";
    } else if (num > 24)
        console.log("calculateMeridian error: num too large, num not in hours");
        return "error";
}

 function convertMStoText(date) { //input as milliseconds, can't seem to input as actual date
    var x = new Date(date); 
    var h = x.getHours; //change to let
    var m = x.getMinutes;
    var meridian = calculateMeridian(h);
    console.log(h + ":" + m + " " + meridian);
}


convertMStoText(today);

输出:

function getHours() { [native code] }:function getMinutes() { [native code] } error

输出图片:

3 个答案:

答案 0 :(得分:2)

var h = x.getHours;
var m = x.getMinutes;

需要

var h = x.getHours();
var m = x.getMinutes();

答案 1 :(得分:2)

计算机完全按照您的要求输出。

看看这一行:

var h = x.getHours;

如果将功能分配给h。你想要的是一个函数调用,分配函数返回的结果:

var h = x.getHours();

它显示:&#34;在对象getHours上调用方法x,不传递任何参数&#34;。这就是空洞的意思。

与分钟相同。

答案 2 :(得分:0)

更新您的功能:

function convertMStoText(date) { //input as milliseconds, can't seem to input as actual date
    var x = new Date(date); 
    var h = x.getHours(); //change to let
    var m = x.getMinutes();
    var meridian = calculateMeridian(h);
    console.log(h + ":" + m + " " + meridian);
}

getHours()和getMinutes()是函数。