在 javascript 或 momentjs 中获取给定的日期格式(指定格式的字符串) [英] Get the given date format (the string specifying the format) in javascript or momentjs

查看:9

问题描述

给定一个日期字符串,如何获取描述该日期字符串的格式字符串?

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

换一种说法,如果没有传递要使用的显式格式,我如何获取 Date() 或 MomentJS(可能每个都不同,这很好)用来解析该日期字符串的格式字符串?

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?

所以给定 '2016-01-01' 它应该输出类似 'YYYY-MM-DD' 的内容,例如.

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

推荐答案

整合来自 Matt Johnson 的回答的信息,一些评论,以及我自己的贡献.

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

使用 Moment.js(版本 2.10.7+),您可以使用 Creation数据 API.Node.js 中的类似内容:

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

输出

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆