将yyyy-mm-dd转换为25日星期二

Converting yyyy-mm-dd into Tuesday 25th

本文关键字:25日 星期二 转换 yyyy-mm-dd      更新时间:2023-09-26

我有一个格式为yyyy-mm-dd的变量集,我想使用JS(jQuery库)将其转换为Tuesday 25th的格式

我试过:

var now = new Date('2013-06-25').format("l jS");
Moment js是一个很好的javascript库,用于处理js的日期对象,并包含灵活的日期对象格式化方法。

这将为您提供您想要的格式。

moment().format('dddd Do');

注意:moment对象是本机日期对象的包装器。

问题1:

jQuery是一个DOM操作库,因此与日期无关。您要么必须使用另一个库,要么编写自己的JavaScript。

问题2:

Date()函数/构造函数在某些浏览器中无法识别该格式,因此您必须自己解析:

var s = '2013-06-25',
    y = +s.substr(0, 4),     // get the year
    m = +s.substr(5, 2) - 1, // get the month
    d = +s.substr(8, 2),     // get the date of the month
    date = new Date(y, m, d);

问题3:

JavaScript中没有自定义日期格式。此外,无法获取日期名称。

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
            'Friday', 'Saturday'];
var formatted = days[date.getDay()] + ' ' + d;

问题4:

无法添加"th"、"nd"等…

if (Math.floor(d % 100 / 10) === 1) { // add 'th' for the 11th, 12th, and 13th
  formatted += 'th';
}
else {
  formatted += {1: 'st', 2: 'nd', 3: 'rd'}[d % 10] || 'th';
}

您可以使用jQuery日期格式插件。你有很多可能性:

https://github.com/phstc/jquery-dateFormat