【问题标题】:How to get current date and time in TypeScript如何在 TypeScript 中获取当前日期和时间
【发布时间】:2019-08-13 20:52:42
【问题描述】:

总结

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

我的尝试

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

代码部分

根据我的理解,代码应该在activate 部分的extension.ts 文件中,我在其中注册命令以实现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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

    let dateTime = new Date()
    

    【讨论】:

      【解决方案2】:

      如果你使用 angular 和 Moment 类型

      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);
      

      【讨论】:

      • "我们现在普遍认为 Moment 是一个处于维护模式的遗留项目。它没有死,但它确实已经完成了。"此报价直接来自 Momentjs 网站上文档页面的项目状态部分。 momentjs.com/docs
      • “使用库”做这样简单的事情是没有建设性的。
      【解决方案3】:

      也许 Luxon 可以成为你的朋友

      对于 Typescript 我真的很喜欢 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

      【讨论】:

      • “使用库”做这样简单的事情是没有建设性的。
      猜你喜欢
      • 2011-01-01
      • 2010-10-03
      • 2017-10-05
      • 2013-10-15
      • 1970-01-01
      • 2015-03-22
      • 2012-12-04
      相关资源
      最近更新 更多