What is the alternate of toLocaleFormat for Chrome?

痴心易碎 提交于 2021-02-09 05:32:13

问题


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.


回答1:


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



回答2:


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

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




回答3:


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.



来源:https://stackoverflow.com/questions/32116926/what-is-the-alternate-of-tolocaleformat-for-chrome

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!