最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 different for each, that's fine) would use to parse that datestring if one didn't pass an explicit format to use?

So given '2016-01-01' it should output something like 'YYYY-MM-DD', for example.

(I am aware this is a simple question and may have an answer somewhere, but it is difficult to word concisely, so I could only find questions and answers about how to parse datestrings or how to display dates. None about how to output the format itself.)

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 different for each, that's fine) would use to parse that datestring if one didn't pass an explicit format to use?

So given '2016-01-01' it should output something like 'YYYY-MM-DD', for example.

(I am aware this is a simple question and may have an answer somewhere, but it is difficult to word concisely, so I could only find questions and answers about how to parse datestrings or how to display dates. None about how to output the format itself.)

Share Improve this question asked Jun 9, 2016 at 18:49 tscizzletscizzle 12.3k16 gold badges58 silver badges98 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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"
发布评论

评论列表(0)

  1. 暂无评论