Get the given date format (the string specifying the format) in javascript or momentjs

久未见 提交于 2019-12-05 06:36:39
tscizzle

Consolidating information from Matt Johnson's answer, some comments, and my own contribution.

With Moment.js (version 2.10.7+), you can use the Creation Data API. Something like this in Node.js:

moment('2016-01-01 00:00:00').creationData().format

outputs

'YYYY-MM-DD HH:mm:ss'

Just as any date parsing is, there is ambiguity about the format of many datestrings due to things such as locale (the order of months and days are switched between the US and Europe, for example). But the above method is sufficient for me.

You can't, without having additional information, such as the locale. For example, 01/12/16 could be Jan 12, 2016, December 1, 2016, or December 16, 2001.

Even when you know the locale, there are several places in the real world where more than one date format is used, depending on context.

See https://en.wikipedia.org/wiki/Date_format_by_country

However, if you are just trying to determine which one of multiple known formats was used to parse the input string, moment has an API for that called Creation Data. For example:

var m = moment("2016/06/10", ["YYYY-MM-DD", "MM/DD/YYYY"], true);
var f = m.creationData().format;  // "MM/DD/YYYY"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!