How to get current date and time in TypeScript

Summary

I'm creating my first extension for VSCode in TypeScript, and want to create a new information message to display current date/time.

What I've tried

I've tried looking for some data/time keyword in the list of vscode key bindings. I've also tried looking for a function to get system date/time on Google only to come across solutions explaining data/time syntax and how to display a specific date/time but nothing to get the CURRENT data/time. I've also looked for it in vscode API documentation.

Code part

According to my understanding the code should be in extension.ts file in activate section where I register the command to implement showInformationMessage function call and send a string to it containing the date/time. So here is the code around the line where I store the current date/time:

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

Desired output: [Current Date/Time]

Actual output: 22 March, 2019 12:45PM

0

3 Answers

To retrieve the current system Date/Time in javaScript/TypeScript you need to create a new Date object using parameterless constructor, like this:

let dateTime = new Date() 

If you use angular and Moment type

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

Maybe Luxon could be your friend

For Typescript I really like Luxon

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

and then

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

See also

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like