Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format a Date/Time in TypeScript?

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

like image 367
Matt Watson Avatar asked Nov 10 '16 11:11

Matt Watson


People also ask

What is the date format in TypeScript?

The following function uses built-in methods to get the year , month , date , hour , minutes and seconds of a specific date and formats it as YYYY-MM-DD hh:mm:ss .

How do I convert dateTime to date format?

The following formula will help you converting date/time format cell to date only in Excel. 1. Select a blank cell you will place the date value, then enter formula =MONTH(A2) & "/" & DAY(A2) & "/" & YEAR(A2) into the formula bar and press the Enter key.


2 Answers

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

like image 142
dougajmcdonald Avatar answered Oct 03 '22 12:10

dougajmcdonald


Option 1: Momentjs:

Install:

npm install moment --save 

Import:

import * as moment from 'moment'; 

Usage:

let formattedDate = (moment(yourDate)).format('DD-MMM-YYYY HH:mm:ss') 

Option 2: Use DatePipe if you are doing Angular:

Import:

import { DatePipe } from '@angular/common'; 

Usage:

const datepipe: DatePipe = new DatePipe('en-US') let formattedDate = datepipe.transform(yourDate, 'dd-MMM-YYYY HH:mm:ss') 
like image 22
WtFudgE Avatar answered Oct 03 '22 12:10

WtFudgE