具有特定语言环境的Javascript日期解析 [英] Javascript Date Parse with specific locale

查看:68
本文介绍了具有特定语言环境的Javascript日期解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从用户输入接收日期/时间对象,并想将它们解析为javascript Date对象.日期格式为:02/06/2018 00:59:03,表示2018年6月2日;英国语言环境. 尽管这看起来非常琐碎且用例非常广泛,但我似乎在

I receive date/time objects from user input, and would like to parse them to a javascript Date object. The date is in the format: 02/06/2018 00:59:03 which means second of june, 2018; 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.

目前,我看到的唯一可用选项是编写自己的解析器,这很不错(当然,这不是必需的,因为明天可能需要其他语言环境),但对我来说似乎是1980年代.

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.

也许我忽略了文档中的某些内容.但是,还有人有其他解决方案吗?将不胜感激.

Maybe I overlooked something in the documentation. But does anyone have any other solution? Would be greatly appreciated.

P.s.我几乎无法想象这还没有被问到,但是我的搜索也没有出现太多.

P.s. I can hardly imagine this has not been asked yet, but my search did not turn up much either.

推荐答案

来自 Date()文档:

注意:使用Date构造函数解析日期字符串(和 强烈建议不要使用Date.parse,它们等效) 浏览器的差异和不一致之处.支持RFC 2822格式 字符串仅按惯例.对ISO 8601格式的支持在以下方面有所不同 仅日期的字符串(例如"1970-01-01")被视为UTC,而不是 本地的.

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

如果输入是结构化的并且格式是恒定的,则编写自己的解析器应该很简单.这是使用正则表达式的一种方法.

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 (i.e. split by a space, then split the first result by / and the second result by :).

这篇关于具有特定语言环境的Javascript日期解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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