Javascript 将返回的字符串 (YYYYMMDD) 转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10607935/
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 Returned String (YYYYMMDD) to Date
提问by kirbyjwilson
I have a string that contains 8 digits that represent a date. For example:
我有一个包含代表日期的 8 位数字的字符串。例如:
20120515
I'd like to compare it with today's date, created in this manner:
我想将它与以这种方式创建的今天的日期进行比较:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
如何将“8 位日期字符串”转换为合适的日期格式以便将其与 currentDate 进行比较?
回答by firexfighterx
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
使用 substring 方法和 substring off 4 个元素并将其分配给您的新日期。然后一次对两个元素进行子串并相应地存储月份和日期。
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
现在您可以用普通运算符比较这两个日期。