javascript - 根据用户的区域设置解析日期

标签 javascript momentjs

我正在尝试使用 moment.js 解析、验证和重新格式化 HTML 表单中的日期。因为该网站正在国际上使用,所以我想将日期重新格式化为 D MMM YYYY 格式(例如:2018 年 4 月 1 日),以尽量减少输入后的混淆。

我的代码中的文本框定义如下:

<input type="text" class="txt-date" name="foo" />

我编写的用于验证/重新格式化的 JavaScript 如下:

$(function () {

    console.log("initial locale: " + moment.locale());
    console.log("initial date format:= " + moment.localeData().longDateFormat('L'));

    var locale = window.navigator.userLanguage || window.navigator.language;
    console.log("changing locale to: " + locale);
    moment.locale(locale);

    console.log("updated locale: " + moment.locale());
    console.log("updated date format = " + moment.localeData().longDateFormat('L'));

    $('input.txt-date').on('change', function() {
        var v = $(this).val();
        if (!v) return; // No value in the textbox

        v = moment(v); // Parse the date
        if (!v.isValid) {
            alert("Invalid Date!");
            return;
        }

        // Re-format the date
        $(this).val(v.format("D MMM YYYY"));
    });
});

这是浏览器日志中的输出:

initial locale = en

initial date format = MM/DD/YYYY

changing locale to: en-GB

updated locale: en

updated date format = MM/DD/YYYY

本质上,moment.js 似乎假设我应该使用英语(美国)区域设置,而不是英语(英国)。根据用户语言更改语言环境(如 here 所示)似乎没有任何区别。

我想要做的就是能够解析用户本地/区域格式的日期字符串(或者 D MMM YYYY,如果他们以这种方式输入)。谁能指点一下?


解决方案

感谢 Phani 的帮助。为了使这项工作正常进行,您需要包含 moment-with-locales.js 文件(可以在“https://momentjs.com/downloads/moment-with-locales.js”中找到,但也包含在 NuGet 包中)。

更新后的 JavaScript 如下:

$(function () {

    // Configure moment to use the user's locale
    moment.locale(window.navigator.userLanguage || window.navigator.language);

    $('input.txt-date').on('change', function () {
        var v = $(this).val();
        if (!v) return; // No value in the textbox

        // Parse the date specified
        var fmt = moment.localeData().longDateFormat('L');
        v = moment(v, [fmt, "D MMM YY", "D MMM YYYY"]);

        // If the date is invalid, warn the user
        if (!v.isValid()) {
            alert("Invalid Date!");
            return;
        }

        // Re-format the date
        $(this).val(v.format("D MMM YYYY"));
    });
});

这种组合适用于我能想到的每个有效日期。

最佳答案

问题是因为 moment locales 丢失或未导入。导入语言环境后,您可以更改语言环境。您可以找到从 CDN 导入的 moment 语言环境(如下)。

请注意,我已根据您的需要将语言环境硬编码为 en-gb

$(function () {          
	console.log(moment.locales())
	console.log("initial locale: " + moment.locale());
	console.log("initial date format:= " + moment.localeData().longDateFormat('L'));

	var locale = window.navigator.userLanguage || window.navigator.language;
	console.log("changing locale to: " + locale);
	moment.locale("en-gb");

	console.log("updated locale: " + moment.locale());
	console.log("updated date format = " + moment.localeData().longDateFormat('L'));

	$('input.txt-date').on('change', function () {
		var v = $(this).val();
		if (!v) return; // No value in the textbox

		v = moment(v); // Parse the date
		if (!v.isValid) {
			alert("Invalid Date!");
			return;
		}

		// Re-format the date
		$(this).val(v.format("D MMM YYYY"));
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- load all available momentjs locales -->
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>

<input type="text" class="txt-date" name="foo" />

关于javascript - 根据用户的区域设置解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46195900/

相关文章:

Javascript:从嵌套键值对中读取键/值

javascript - redux - 当一个资源依赖于另一个资源时,如何适本地更新它们

javascript - 修改和切换 float 元素的位置

javascript - 如何在 Javascript/Jquery 中获取包含单击文本的元素?

javascript - 获取两个跳过办公时间的日期时间之间的时差

javascript - 没有闰日的两个日期之间的差异

jquery - 日期范围选择器无法正常工作

javascript - 使用css/js切换黑白图像的颜色

javascript - Moment.js 在 Mozilla Firefox 中显示无效日期

javascript - 在某些日期失败的时刻