简体   繁体   English

解析并格式化javascript日期:dd M YYYY到YYYY-mm-dd

[英]Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like: 我有一个约会,看起来像:

30 Apr 2015

How do I parse and display the date like this (without Moment.js)? 如何解析和显示这样的日期(没有Moment.js)?

2015-04-31 (or YYYY-mm-dd)

The easiest thing to do might be to use moment.js . 最简单的操作可能是使用moment.js

If you prefer rolling your own solution in vanilla JS, this will work: 如果您希望在Vanilla JS中滚动自己的解决方案,则可以使用:

var padZero = function (integer) { 
    return integer < 10 ? '0' + integer : '' + integer 
};

var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' + 
    (padZero(myDate.getMonth()+1)) + '-' + 
    (padZero(myDate.getDate()));

console.log(myDateString); // 2015-04-30

The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :) 解析部分很容易...尽管在您的示例中它会失败,因为四月没有第31天:)

var x = new Date("30 Apr 2015");

Formatting the date is a little trickier. 格式化日期有点棘手。 You have a few options. 您有几种选择。 Date natively supports several output methods ( .toDateString() , .toLocaleDateString() , etc) but none of them match the format you've given. Date本机支持几种输出方法( .toDateString() .toLocaleDateString()等),但是它们都不符合您指定的格式。 It does, however, allow you to individually select the day, month and year values for the date. 但是,它确实允许您分别选择日期的日,月和年值。 So, you can assemble them manually: 因此,您可以手动组装它们:

console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())

Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate() ). 请注意, .getMonth()返回基于0的索引,并且不会填充到两位数, .getDay()获取星期几索引,而不是月几(即.getDate() )。

However, your better choice is to take a look at moment.js , which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. 但是,最好的选择是看一下moment.js ,它提供了通过任意格式的字符串进行格式化的功能,类似于您期望从其他语言获得的格式。 Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists. 除非您由于某种原因无法引入另一个库,否则我认为这是一类问题,在这种情况下,可以使用已经存在的非常好的解决方案。

Use moment.js 使用moment.js

Convert your date like this: 像这样转换日期:

var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30

DEMO 演示

you can do that easy with 您可以轻松做到

//define Date
    var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
    var months = {
    Jan:'01',
    Feb:'02',
    Mar:'03',
    Apr:'04',
    May:'05'
    };
// split our Date and rearrange as yyyy-mm-dd
    var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
    alert(reform);// return 2015-04-31

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

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