Home > Web Front-end > JS Tutorial > How to convert strings and dates in javascript

How to convert strings and dates in javascript

藏色散人
Release: 2023-01-05 16:10:47
Original
5832 people have browsed it

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.

How to convert strings and dates in javascript

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; 
},
Copy after login

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;
 },
Copy after login

 [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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template