How to format JavaScript date in relation to browser culture?

I need to format a JavaScript Date object. It should display the date and time in short format in relation to the culture used by the browser, for example:

20/10/2011 10:20 PM 10.20.2011 22:20 

How to do it (preferably with jQuery)?

+2
source share
3 answers

The Date () object will give you client time ( live demo here ):

 var now=new Date(); alert(now.toLocaleString()); 

JS and jQuery do not have a built-in formatting function. To format it differently, use the format() function (1.2kb) here, and then the following code will produce a format like "10/10/2012 8:50 pm":

 var now=new Date(); alert( now.format("mm/dd/yy h:MM:ss TT") ); 
+3
source

Browsers use system settings for date formats or use their own (often US-oriented) settings.

There is a Date.prototype.toLocaleDateString () method, which should return a date based on the current system settings, however, it is implementation dependent and completely unreliable due to inconsistency between browsers.

eg. for me December 13, 2011:

  • Safari returns 13 December 2001
  • Firefox 12/13/2011
  • Opera Tuesday December 13, 2011
  • Chrome Tuesday, December 13, 2011
  • IE 6 Tuesday, 13 December, 2011

Thus, only Safari and IE actually use the system settings, it seems that the developers of other browsers are either too lazy, indifferent or uninformed to host non-American users.

An alternative is to either ask the user which format he prefers, or simply use a unique format, for example. 13-Dec-2011 will be understood by everyone. If you really should use only numbers, then the ISO-8601 format should succeed: 2011-12-13 with added benefits that are easy to sort.

Some functions that print a short date in the above formats:

 // format: 2011/12/5 function shortDate1(obj) { obj = obj || new Date(); return obj.getFullYear() + '/' + (obj.getMonth() + 1) + '/' + obj.getDate(); } // format: 2011/12/05 // (padded single digit month and day) function shortDate2(obj) { function z(n) { return (n < 10? '0' : '') + n; } obj = obj || new Date(); return obj.getFullYear() + '/' + z(obj.getMonth() + 1) + '/' + z(obj.getDate()); } // format: 15-Dec-2011 function shortDate3(obj) { obj = obj || new Date(); function z(n) { return (n < 10? '0' : '') + n; } months = ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']; return [z(obj.getDate()),months[obj.getMonth()],obj.getFullYear()].join('-'); } 
+3
source

It is useful to know if the system uses day-month or month-day in its string methods, mainly for setting the order of user inputs. toLocaleString is great for displaying a known date - and is international.

  Date.dmOrder=(function(){ return Date.parse('2/6/2009')> Date.parse('6/2/2009'); })() if(Date.dmOrder)// ask for the date first else // ask for the month first 
+2
source

Source: https://habr.com/ru/post/949438/


All Articles