4

I am trying to convert format of date using Javascript. I found a method called toLocaleFormat.

 <script>
  var today = new Date();
  var formatted_string = today.toLocaleFormat('%d/%m/%Y at %H:%M:%S %p (%Z)');
  document.write(formatted_string);
 </script>

But its working only in firefox. I want to know an alternate method for this, which will work on all the browsers. Kindly help me to do this. Thanks in advance.

Can Can
  • 3,216
  • 5
  • 29
  • 53

3 Answers3

7

JavaScript in itself doesnt have advanced parse and formatting functions for dates. Most of the time we depend on framework we are using in application or any date based plugins like this one

http://momentjs.com/

To format dateObject

moment(dateObject).format('MMMM Do YYYY, h:mm:ss a'); // August 20th 2015, 5:09:08 pm
Rahul Jujarey
  • 151
  • 1
  • 4
0

you can use toLocaleDateString() to get "dd.mm.yyy" format date

Example:var date = new Date().toLocaleDateString();

emre ozcan
  • 51
  • 4
0

You can use a library if you really want to keep using that method of specifying the date format (using a format string, inherited from a similar C language function), but it is important to consider that that whole way of formulating dates is deprecated in js.

The recommended alternative is 'Intl.DateTimeFormat' which is not a direct replacement - it does not include any way to explicitly specify a date format as a string, which is probably the idea (this allows more leeway for the system to formulate a representation suited to the user).

Also consider that you could still build a date with an explicit format by manually concatenating the components, but that is certainly more cumbersome and less dynamic.

Tom
  • 15,404
  • 8
  • 60
  • 70