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

前端 未结 2 1623
遥遥无期
遥遥无期 2020-12-06 18:04

Given a datestring, how can I get the format string describing that datestring?

Put another way, how can I get the format string that Date() or MomentJS (might be di

2条回答
  •  盖世英雄少女心
    2020-12-06 18:28

    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"
    

提交回复
热议问题