【问题标题】:Uncaught TypeError: **now.toUTCString** is not a function at HTMLButtonElement未捕获的类型错误:**now.toUTCString** 不是 HTMLButtonElement 的函数
【发布时间】:2021-07-10 16:34:53
【问题描述】:

当我不添加任何时区时,JS 运行良好,但当我尝试回显巴巴多斯时区时,我收到以下与 now.toUTCString 相关的错误。我该如何解决这个问题?

未捕获的类型错误:now.toUTCString 不是函数 在 HTMLButtonElement。 (index.js:24)

const txtTrollName = document.getElementById('txtTrollName');
const txtTrollMsg = document.getElementById('txtTrollMsg');
const btnNewTrollMsg = document.getElementById('btnNewTrollMsg');

function updateTrollbox(trollPost) {
    var trollData = '<p><b>' + trollPost.troll;
    trollData += '</b> said: ' + trollPost.message;
    trollData += ' - <small>' + trollPost.date + '</small><p>';

    // inject into HTML list element
    var currentTrollbox = document.getElementById('trollbox').innerHTML;
    document.getElementById('trollbox').innerHTML = currentTrollbox + trollData;
}

// new trollbox entry
btnNewTrollMsg.addEventListener('click', e => {
    const troll = txtTrollName.value;
    const msg = txtTrollMsg.value;
   // const now = new Date();
    const now = new Date().toLocaleString('en-US', { timeZone: 'America/Barbados' });
    const trollPost = {
        troll: troll,
        message: msg,
        date: now.toUTCString()
    };

    // update posts
    updateTrollbox(trollPost);

    // clear textbox
    document.getElementById('txtTrollName').value = '';
    document.getElementById('txtTrollMsg').value = '';
    console.clear();
});

【问题讨论】:

    标签: javascript node.js timezone


    【解决方案1】:

    这是因为 const now = new Date().toLocaleString 已经将其转换为字符串。您正在尝试对字符串使用 toUTCString 方法。您应该在日期对象上应用 toUTCString() 方法。

    【讨论】:

    • 谢谢。我将 date: now.toUTCString() 更改为 date: now 并且成功了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2019-05-24
    相关资源
    最近更新 更多