简体   繁体   中英

Javascript - Convert date string to US date format

I have a string named regdate and the value is 16-4-2017 00:00:00

Now I have been trying for a few hours to convert this string to this kind of format: 4/16/2017 12:00:00 AM

I know this question could be duplicated but I have been looking on the internet for hours now.

Method 1 - Parse with regular expression, format output with toLocaleString

In this code snippet, the string.match method is used to parse the date string. A date object is then created with the date parts, and toLocaleString("en-US") is used to get the US date format:

 function convertDate(regdate) { var m = regdate.match(/(\\d+)-(\\d+)-(\\d+)\\s+(\\d+):(\\d+):(\\d+)/); var date = new Date(m[3], m[2] - 1, m[1], m[4], m[5], m[6]); return date.toLocaleString("en-US"); } 
 Date: <input id="txtDate" type="text" value="16-4-2017 00:00:00" /> <button onclick="console.log(convertDate(document.getElementById('txtDate').value))">Convert</button> 

Method 2 - Parse and replace with regular expression

In the second code snippet, the string.replace method is used to modify the date string: a regular expression parses the original date string, and a replacement function recombines the various parts:

 function convertDate(regdate) { return regdate.replace(/(\\d+)-(\\d+)-(\\d+)\\s+(\\d+):(\\d+):(\\d+)/, function(m, v1, v2, v3, v4, v5, v6) { var hour24 = parseInt(v4, 10); var hour12 = hour24 % 12 || 12; var ampm = hour24 < 12 ? "AM" : "PM"; return `${v2}/${v1}/${v3} ${hour12}:${v5}:${v6} ${ampm}`; }); } 
 Date: <input id="txtDate" type="text" value="16-4-2017 00:00:00" /> <button onclick="console.log(convertDate(document.getElementById('txtDate').value))">Convert</button> 

Method 3 - Parse with datejs library, format output with toLocaleString

If you don't mind using an external library, you can convert the string to a date with datejs and use date.toLocaleString("en-US") to format the output:

 var date = Date.parse("16-4-2017 00:00:00"); console.log(date.toLocaleString("en-US")); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script> 

Now finished!!

 var time = "16-4-2017 13:00:00"; var date = time.split(' ')[0].split('-'); //now date is ['16', '4', '2017']; time = time.split(' ')[1].split(':'); //now time is ['13', 00', 00'] var dateFull = new Date(date[2], date[1], date[0], time[0], time[1], time[2]); var dateString = (dateFull.getMonth()) + dateFull.toString().substring(0, dateFull.toString().indexOf('G')).substring(7).replace(' ', '/').replace(' ', '/'); if (dateFull.getHours() > 12) dateString = dateString.replace(dateFull.getHours(), dateFull.getHours() - 12) + 'PM'; else if (dateFull.getHours() == 12) dateString += 'PM'; else dateString += 'AM'; console.log(dateString); 

 var q = new Date(Date.parse('2017-4-16 00:00:00')); console.log(q.toLocaleDateString()+q.toLocaleTimeString()); 

This should help. But check the input format of the date. The format you posted will always give you NaN

Just another example, but a little more concise:

 // Reformat 16-4-2017 00:00:00 to 4/16/2017 12:00:00 AM function reformatString(s) { var b = s.split(' '); var d = b[0].replace(/(\\d+)-(\\d+)-(\\d+)/,'$2/$1/$3'); var t = b[1].split(':'); return d + ' ' + (t[0]%12 || 12) + ':' + t[1] + ':' + t[2] + (t[0] < 12? ' AM' : ' PM'); } console.log(reformatString('16-4-2017 00:00:00')); 

However, formatting a string in US format with just digits is very ambiguous. Far better to use an unambiguous format, such as using the month name rather than number, eg April 16, 2017 12:00:00 AM

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">

  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="123" roles="tomcat"/>
  <user username="both" password="123" roles="tomcat,role1"/>
  <user username="role1" password="123" roles="role1"/>
  <user username="souvik" password="xyz123" roles="manager-gui,manager-script,manager-jmx,manager-status" />
</tomcat-users>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM