如何在TypeScript中获取当前数据和时间

时间:2019-03-22 19:50:10

标签: typescript

摘要

我正在用TypeScript创建VSCode的第一个扩展,并希望创建一条新的信息消息以显示当前日期/时间。

我尝试过的事情

我试图在vscode键绑定列表中寻找一些data / time关键字。我还尝试过寻找一种在Google上获取系统日期/时间的功能,只是遇到了解释数据/时间语法以及如何显示特定日期/时间的解决方案,但没有任何方法来获取当前数据/时间。我也在vscode API文档中找到了它。

代码部分

根据我的理解,代码应位于extension.ts部分的activate文件中,在该文件中我注册了用于实现showInformationMessage函数调用的命令,并向其中发送包含日期/时间的字符串。所以这是我存储当前日期/时间的那行代码:


  let disposableShowTime = vscode.commands.registerCommand(
    "extension.showTime",
    () => {
      // Display a message box to the user
      let dateTime = "22 March, 2019 12:45PM"; // store current data/time instead
      vscode.window.showInformationMessage("Current time: " + dateTime);
    }
  );

所需的输出[Current Date/Time]

实际输出22 March, 2019 12:45PM

3 个答案:

答案 0 :(得分:3)

要在javaScript / TypeScript中检索当前系统的日期/时间,您需要使用无参数构造函数创建一个新的Date对象,如下所示:

let dateTime = new Date()

答案 1 :(得分:2)

如果使用角和矩类型

import * as moment from 'moment';
...
//Change DATE_TIME_FORMAT by the format need
const DATE_TIME_FORMAT = 'YYYY-MM-DDTHH:mm'; 
let _now: Moment;
_now = moment(new Date(), DATE_TIME_FORMAT);

答案 2 :(得分:0)

也许 Luxon 可以成为你的朋友

对于打字稿,我真的很喜欢 Luxon

npm install --save luxon
npm install --save-dev @types/luxon

然后

import { DateTime } from 'luxon';
DateTime.now().toLocaleString(DateTime.DATE_FULL);

另见https://moment.github.io/luxon/docs/manual/formatting.html