简体   繁体   English

使用javascript将数字转换为日期

[英]Convert number into date using javascript

I have date in without "/" in text field and it is in mm/dd/yy format. 我在文本字段中没有“ /”的日期,并且它是mm/dd/yy格式。 We received input in this format 03292014. I want to get month,date and year from this number like 03/29/2014 我们收到的格式为03292014的输入。我想从该数字中获取月,日和年,如2014年3月29日

var m = new Date(3292014*1000)

console.log(m.toGMTString())

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 : 或将输入转换为标准的“ YYYY-MM-DD”格式:

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 . 规格: http : //es5.github.io/#x15.9.1.15


According to Xotic750's comment , in case you just want to change the format : 根据Xotic750的评论 ,万一您只想更改格式:

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

Get the components from the input, then you can create a Date object from them. 从输入中获取组件,然后可以从它们创建Date对象。 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);

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

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