Using moment.js, how to display the current date format for the user?

China☆狼群 提交于 2019-12-30 09:28:08

问题


Given a text field, I want to have a suitable placeholder. A typical placeholder will be something like: "mm/dd/yyyy".

However, I would like to use locale-aware dates using moment.js.

This means that I will be specifying "l" as the moment.js date format, howe do I determine the date format that moment.js will be using in this case?

The user will not understand what "l" means, so using this value in the placeholder text makes very little sense.

Specifically, I am hoping to be able to access something like moment's internal "defaultLongDateFormat". (Though that is merely a default - moment.js probably updates it or has some other mapping at runtime for locale-aware date formats - I would like to access that mapping.)

EDIT:

There are multiple downvotes (who aren't explaining why they're downvoting it).

I think this is because they arent' understanding the question, so here are some examples:

I want a function such that: getFormat("l") -> "mm/dd/yyyy", or equivalent for the US locales. getFormat("l") -> "dd/mm/yyyy", or equivalent, for the AU locales.

I do not want to format a given date, or to parse a given date - I merely want to determine it's user-friendly format given an arbitruary moment.js format, specifically, for 'l'.


回答1:


I don't think it's exposed nicely, but if the browser has its language configured correctly you can do something like this:

var lang = navigator.languages ? navigator.languages : navigator.language;

moment().locale(lang).localeData()._longDateFormat['L']

Languages behave slightly differently depending on which browser you're using, so don't know how reliable this is.




回答2:


Follow up to Adam R's answer:

Seems to have been exposed by now:

localeData.longDateFormat(dateFormat);

returns the full format of abbreviated date-time formats LT, L, LL and so on

(source: http://momentjs.com/docs/)

Get the currently used locale data by moment.localeData()



来源:https://stackoverflow.com/questions/31374376/using-moment-js-how-to-display-the-current-date-format-for-the-user

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