Home >Web Front-end >JS Tutorial >How to convert strings and dates in javascript
Methods for converting JavaScript strings and dates: 1. Convert dates to strings through the "if (month.length == 1) {...}" method; 2. Convert dates to strings through "if (dateArr [1].indexOf("0") == 0){...}" to convert the string into a date.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
JS date and string conversion
1. Convert date to string
dateToString: function(date){ var year = date.getFullYear(); var month =(date.getMonth() + 1).toString(); var day = (date.getDate()).toString(); if (month.length == 1) { month = "0" + month; } if (day.length == 1) { day = "0" + day; } var dateTime = year + "-" + month + "-" + day; return dateTime; },
2. Convert string to date
stringToDate : function(dateStr,separator){ if(!separator){ separator="-"; } var dateArr = dateStr.split(separator); var year = parseInt(dateArr[0]); var month; //处理月份为04这样的情况 if(dateArr[1].indexOf("0") == 0){ month = parseInt(dateArr[1].substring(1)); }else{ month = parseInt(dateArr[1]); } var day = parseInt(dateArr[2]); var date = new Date(year,month -1,day); return date; },
[Recommended learning:javascript advanced tutorial】
The above is the detailed content of How to convert strings and dates in javascript. For more information, please follow other related articles on the PHP Chinese website!