How do you format a Date/Time in TypeScript?

Matt  Watson picture Matt Watson · Nov 10, 2016 · Viewed 426.9k times · Source

I've been having some trouble trying to get a Date object in TypeScript to format the way I want it to.

I have a class Module which is defined as:

export class Module {

    constructor(public id: number, public name: string, public description: string, 
                 public lastUpdated: Date, public owner: string) { }

    getNiceLastUpdatedTime(): String {

        let options: Intl.DateTimeFormatOptions = {
            day: "numeric", month: "numeric", year: "numeric",
            hour: "2-digit", minute: "2-digit"
        };

        return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options);
    }
}

When I call the method with the following code:

    let date = new Date(1478708162000); // 09/11/2016 16:16pm (GMT)
    let module = new Module(1, "Test", "description", date, "test owner");
    console.log(module.getNiceLastUpdatedTime());

I end up with the following printed in the console:

'9 November 2016 16:16:02 GMT'

What I want to see is:

09/11/2015 16:16

I've had a look at the documentation at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString and I still can't see what I'm doing wrong (I know this is a JavaScript API documentation but I'm pretty sure that's what TypeScript is using under the hood).

Answer

dougajmcdonald picture dougajmcdonald · Nov 10, 2016

If you want the time out as well as the date you want Date.toLocaleString().

This was direct from my console:

> new Date().toLocaleString()
> "11/10/2016, 11:49:36 AM"

You can then input locale strings and format string to get the precise output you want.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString