简体   繁体   English

具有特定语言环境的 Javascript 日期解析

[英]Javascript Date Parse with specific locale

I receive date/time objects from user input, and would like to parse them to a javascript Date object.我从用户输入接收日期/时间对象,并希望将它们解析为 javascript Date 对象。 The date is in the format: 02/06/2018 00:59:03 which means second of june, 2018;日期格式为: 02/06/2018 00:59:03 ,表示 2018 年 6 月的第二日; UK locale.英国地区。 Although this seems extremely trivial and a super wide use case scenario, I can't seem to find anything in the documentation how to specify the locale I wish to use for parsing.尽管这看起来非常简单且用例场景非常广泛,但我似乎无法在文档中找到任何关于如何指定我希望用于解析的语言环境的内容。

What the parser does is simply assume I am using US locale format, which defaults to having first the month, then the day, and then the year, so it mixes up month and day.解析器所做的只是假设我使用的是美国语言环境格式,默认情况下首先是月份,然后是日期,然后是年份,因此它混合了月份和日期。

Currently the only available option I see is writing my own parser, which is fine ish (it is not, of course, as I might tomorrow need another locale), but seems a little 1980ies to me.目前我看到的唯一可用选项是编写我自己的解析器,这很好(当然不是,因为我明天可能需要另一个语言环境),但对我来说似乎有点 1980 年代。

Maybe I overlooked something in the documentation.也许我忽略了文档中的某些内容。 But does anyone have any other solution?但是有人有其他解决方案吗? Would be greatly appreciated.将不胜感激。

Ps I can hardly imagine this has not been asked yet, but my search did not turn up much either. Ps 我很难想象这还没有被问到,但我的搜索也没有出现太多。

From MDN's Date() documentation:来自 MDN 的Date() 文档:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.注意:由于浏览器的差异和不一致,强烈建议不要使用 Date 构造函数(和 Date.parse,它们是等效的)解析日期字符串。 Support for RFC 2822 format strings is by convention only.仅按惯例支持 RFC 2822 格式字符串。 Support for ISO 8601 formats differs in that date-only strings (eg "1970-01-01") are treated as UTC, not local.对 ISO 8601 格式的支持的不同之处在于,仅将日期字符串(例如“1970-01-01”)视为 UTC,而不是本地。

If your input is structured and the format is constant, writing your own parser should be straightforward.如果您的输入是结构化的并且格式是恒定的,那么编写您自己的解析器应该很简单。 Here's an approach using a regular expression.这是使用正则表达式的方法。

 var dateString = '02/06/2018 00:59:03'; var dateParser = /(\\d{2})\\/(\\d{2})\\/(\\d{4}) (\\d{2}):(\\d{2}):(\\d{2})/; var match = dateString.match(dateParser); var date = new Date( match[3], // year match[2]-1, // monthIndex match[1], // day match[4], // hours match[5], // minutes match[6] //seconds ); console.log('Input: ' + dateString); console.log('Output (en-US): ' + date.toLocaleString('en-US')); console.log('Output (en-GB): ' + date.toLocaleString('en-GB'));

Alternatively, string splitting would be pretty easy as well (ie split by a space, then split the first result by / and the second result by : ).可替换地,串分割将是很容易的,以及(即,由一个空间分割,然后分裂由第一结果/和由所述第二结果: )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM