javascript 使用javascript将数字转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22116192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert number into date using javascript
提问by Carlos
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
我在文本字段中有没有“/”的日期,它是mm/dd/yy
格式。我们收到了这种格式的输入 03292014。我想从这个数字中获取月份、日期和年份,例如 03/29/2014
var m = new Date(3292014*1000)
console.log(m.toGMTString())
回答by leaf
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)/, '--'
));
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)/, '//'
);
input; // "03/29/14"
回答by Guffa
Get the components from the input, then you can create a Date
object from them. Example:
从输入中获取组件,然后您可以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);