javascript:如何解析日期字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4680028/
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
javascript: how to parse a date string
提问by Bin Chen
The format is: MMDDHHMM
格式为:MMDDHHMM
I want to take month, day, hour, minute individually, how to do that?
我想分别取月、日、小时、分钟,该怎么做?
采纳答案by Thai
var dateString = '13011948';
The length of the text is fixed and always at the same position. Then you can just use substr
to cut them into parts and use parseInt
to convert them to number.
文本的长度是固定的并且总是在相同的位置。然后你可以使用substr
将它们切割成部分并用于parseInt
将它们转换为数字。
var month = parseInt(dateString.substr(0, 2), 10),
day = parseInt(dateString.substr(2, 2), 10),
hour = parseInt(dateString.substr(4, 2), 10),
minute = parseInt(dateString.substr(6, 2), 10);
Or instead, put it in a single date object.
或者,将其放在单个日期对象中。
var date = new Date();
date.setMonth (parseInt(dateString.substr(0, 2), 10) - 1);
date.setDate (parseInt(dateString.substr(2, 2), 10));
date.setHours (parseInt(dateString.substr(4, 2), 10));
date.setMinutes (parseInt(dateString.substr(6, 2), 10));
回答by Mark Biek
If you're guaranteed that it's always going to be in MMDDHHMM format, you could parse it with a simple regex.
如果你保证它总是采用 MMDDHHMM 格式,你可以用一个简单的正则表达式来解析它。
var d = "01121201";
var m = /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/.exec(d);
console.log(m);
which would output
哪个会输出
["01121201", "01", "12", "12", "01"]
But using the actual date functions is better if possible.
但如果可能的话,使用实际的日期函数会更好。
You could do something like the following to take the result of the regex match above to create a true Javascript Date object:
您可以执行以下操作以获取上述正则表达式匹配的结果以创建真正的 Javascript Date 对象:
//The year will default to the current year
var realDate = new Date();
realDate.setMonth(m[1]);
realDate.setDate(m[2]);
realDate.setHours(m[3]);
realDate.setMinutes(m[4]);
回答by stephen776
EDIT
编辑
The moment.js library found herelooks amazing for this!
在这里找到的 moment.js 库看起来很棒!
END EDIT
结束编辑
this should help...working with Dates
这应该会有所帮助...使用日期
回答by niksvp
There are several method in javascript Date object which would get you those parameters
javascript Date 对象中有几种方法可以为您提供这些参数
var curdate = new Date();
var mday = curdate.getDate(); //returns day of month
var month = curdate.getMonth(); //returns month 0-11
var hours = curdate.getHours(); //returns hours 0-23
var minutes = curdate.getMinutes(); //returns minutes 0-59
Check this
检查这个
If you do not have date object you can parse it using
如果您没有日期对象,您可以使用
var curdate = Date.parse("Jan 1, 2010");
To parse date to your specific format refer this
要将日期解析为您的特定格式,请参阅此