You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在vscode.commands.registerCommand回调中使用Date()显示时间失败的问题

问题解决:VS Code扩展中Date方法显示函数代码而非时间结果

你遇到的核心问题是:没有调用getHours()和getMinutes()方法,只是把这两个方法的引用直接拼接到字符串里,所以提示框显示的是函数本身的代码文本,而不是执行后得到的小时、分钟数值。

修改后的代码如下:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    
    console.log('Congratulations, your extension "helloworld" is now active!');

    const disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
        vscode.window.showInformationMessage('Hello VS Code!');
    });

    const disposable1 = vscode.commands.registerCommand('helloworld.helloTime', () => {
        const d = new Date();
        // 给方法加上括号,执行后获取实际的时间数值
        vscode.window.showInformationMessage(`Hello, the current time is ${d.getHours()}:${d.getMinutes()}`);
    });

    context.subscriptions.push(disposable);
    context.subscriptions.push(disposable1);
}

export function deactivate() {}

补充说明:

  • 在JavaScript/TypeScript中,d.getHours代表的是这个方法本身的引用,只有加上括号()才会触发方法执行,返回对应的小时数(同理d.getMinutes()返回分钟数)。
  • 示例中使用了ES6模板字符串(反引号包裹,变量通过${}嵌入),比传统的字符串加号拼接更简洁易读,你也可以用原有的拼接方式:'Hello, the current time is ' + d.getHours() + ':' + d.getMinutes(),效果一致。

内容的提问来源于stack exchange,提问作者Jeff Higgins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:33:18