Endless
Endless

Reputation: 37815

display date as datetime input would

My problem is this: chromes datetime-local is displayed the way my OS is configured (currently dd/mm/yyyy hh:ss) (24h clock) (en-US)

The best way I have came up with to display the date the same way. Was to make an input with readonly and no borders but that's not optimal. i need to have it in a variable (string) and be able to save it and perhaps send a email with the same format (just a example)

The secound best thing was to use Date.toLocalString(); but it's still not the same as the system or input format

From what i understand and found out

i don't wish to change the date format/mask of the input (cuz that would not follow the clients wishes) but i would considering setting the input format/mask to the same format as toLocalString to get the same behavior if that is even possible???


enter image description here

http://plnkr.co/edit/nAfgdkPrFqjk6pyBjs8K?p=preview


but now when we have datetime-local is there no way we can get the system format from the input field?

Upvotes: 3

Views: 608

Answers (1)

PhistucK
PhistucK

Reputation: 2546

(Since this is apparently a Google Chrome question, this answers the question in the same context)

Chrome (and latest versions of other browsers) has an internationalization JavaScript API. It lets you format numbers and dates and compare strings according to the current (or any supported) locale.

Using Intl.DateTimeFormatter, you can format the date you get from the input (new Date(dateInputElement.valueAsNumber) will give you the raw date object) -

var formatter = new Intl.DateTimeFormat();
console.log(formatter.format(new Date(dateInputElement.valueAsNumber)));

You can configure the DateTimeFormatter using an options object when you construct it -

var formatter = new Intl.DateTimeFormat((new Intl.DateTimeFormat).resolvedOptions().locale,{year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric"});
console.log(formatter.format(new Date(dateInputElement.valueAsNumber)));

Upvotes: 1

Related Questions