Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 262
tscizzle Avatar asked Jun 09 '16 18:06

tscizzle


1 Answers

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.

like image 158
tscizzle Avatar answered Oct 17 '22 10:10

tscizzle