Convert number into date using javascript

2019-08-31 10:56发布

问题:

I have date in without "/" in text field and it is in mm/dd/yy format. We received input in this format 03292014. I want to get month,date and year from this number like 03/29/2014

var m = new Date(3292014*1000)

console.log(m.toGMTString())

回答1:

You could do this :

var m = '03292014'.match(/(\d\d)(\d\d)(\d\d\d\d)/);
var d = new Date(m[3], m[1] - 1, m[2]);

Or convert the input into a standard "YYYY-MM-DD" format :

var d = new Date('03292014'.replace(
    /(\d\d)(\d\d)(\d\d\d\d)/, '$3-$1-$2'
));

Specs : http://es5.github.io/#x15.9.1.15.


According to Xotic750's comment, in case you just want to change the format :

var input = '03292014';
input = input.replace(
    /(\d\d)(\d\d)\d\d(\d\d)/, '$1/$2/$3'
);
input; // "03/29/14"


回答2:

Get the components from the input, then you can create a Date object from them. Example:

var input = '03292014';

var year = parseInt(input.substr(4), 10);
var day = parseInt(input.substr(2, 2), 10);
var month = parseInt(input.substr(0, 2), 10);

var date = new Date(year, month - 1, day);