Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date format (international settings)

The javascript Date.toLocaleDateString() is silly.

What I need is a function that allows me to simplify the date according to preference.

It would be nice if there were a function which would read the browser date formats (plural) and take an optional parameter telling it which format to use.

I'll explain: "MM/DD/YYYY" works great for the US and anyone willing to put up with them/us. "DD/MM/YYYY" is the most common format for people interested in a short simple date format. "Weekday, Month DayOfMonth, Year" is only useful if you want a super-long and language-dependent output.

I could use this:

var s = "/";
if(locale=='us')
  var dateString = Date.getDate()+s+Date.getDay()+s+Date.getFullYear();
else
  var dateString = Date.getDay()+s+Date.getDate()+s+Date.getFullYear();

But I'm looking for a more elegant solution that will allow me to store a date mask or format string so people can change the way their dates are displayed according to their own tastes. (Even the super-long language-dependent one if they like it enough.)

Should I re-prototype the Date.toString() method to interpret parameters? Is there a better way?

like image 232
Luke Avatar asked May 14 '26 03:05

Luke


2 Answers

You can use DateTimeFormat Api.

var now = new Date(0)
console.log(new Intl.DateTimeFormat('en-US').format(now)); //12/31/1969
console.log(new Intl.DateTimeFormat('en-GB').format(now)); //31/12/1969

See this link for Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

PROS:

  • you don't have to add more libraries to you project, increasing the bundle size.
  • you don't have to worry about browser support, because almost every browser supports it. https://caniuse.com/#search=intl

PS: if you don't care about bundle size and you want something more "user friendly" and easy to use see moment.js or luxon, they are both great libraries for date operations.

like image 101
Kevin Oliveira Avatar answered May 15 '26 18:05

Kevin Oliveira


I ran into a very powerful library that takes care of dates and generic formatting: http://blog.stevenlevithan.com/archives/date-time-format (Wrong link) http://jawe.net/wiki/dev/jsdateformat/home

Is pretty powerful and configurable. (It supports java-style formats that I need, such as the "MEDIUM" date format)

Moment appears to be useful and feature-full (just no Medium format): https://github.com/timrwood/moment

like image 32
harningt Avatar answered May 15 '26 19:05

harningt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!