我在文本字段中没有“/”的日期,它是mm/dd/yy
格式。我们收到了这种格式的输入03292014.我想从这个数字中得到月份,日期和年份,例如03/29/2014
var m = new Date(3292014*1000)
console.log(m.toGMTString())
答案 0 :(得分:4)
你可以这样做:
var m = '03292014'.match(/(\d\d)(\d\d)(\d\d\d\d)/);
var d = new Date(m[3], m[1] - 1, m[2]);
或将输入转换为标准的“YYYY-MM-DD”格式:
var d = new Date('03292014'.replace(
/(\d\d)(\d\d)(\d\d\d\d)/, '$3-$1-$2'
));
规格:http://es5.github.io/#x15.9.1.15。
根据Xotic750's comment,如果您只想更改格式:
var input = '03292014';
input = input.replace(
/(\d\d)(\d\d)\d\d(\d\d)/, '$1/$2/$3'
);
input; // "03/29/14"
答案 1 :(得分:1)
从输入中获取组件,然后您可以从它们创建Date
对象。例如:
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);