Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormat in TypeScript

Tags:

typescript

I want to display a time string in 24 hour format and thought it would be easy in TypeScript. But I can't use the Date.toLocaleTimeString() with options for some reason. Any idea why? They are defined in a separate interface definition.

interface Date {     toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;     toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; } 

The other option is to use Intl.DateTimeFormat but the constructors return a Collator?

var DateTimeFormat: {     new (locales?: string[], options?: DateTimeFormatOptions): Collator;     new (locale?: string, options?: DateTimeFormatOptions): Collator;     (locales?: string[], options?: DateTimeFormatOptions): Collator; 

Is it a copy paste bug in lib.d.ts (same for NumberFormat) or how am I supposed to use them?

Hopefully it's an easy fix, I'm pretty new to TypeScript so I might have missed something.

like image 742
tengl Avatar asked Mar 07 '14 09:03

tengl


People also ask

What is the date format in TypeScript?

We used the addition (+) operator to add a space in the middle of the strings to get the date formatted as yyyy-mm-dd hh:mm:ss .

How do I change the date format in TypeScript?

To format a date or time in TypeScript, we can use the date's toLocaleString method. const s = new Date(). toLocaleString(); to create a new Date object and then call toLocaleString on it to return a string that has the formatted datetime of the current time formatted according to the current locale.

How do I convert a string to a date in TypeScript?

Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.


1 Answers

This should work...

var displayDate = new Date().toLocaleDateString();  alert(displayDate); 

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!  alert(displayDate); 
like image 167
Fenton Avatar answered Oct 27 '22 05:10

Fenton