Javascript Data Type How to - Convert date string 'Mon, 15 Jul 2013 09:27:39 -0700' to another format








Question

We would like to know how to convert date string 'Mon, 15 Jul 2013 09:27:39 -0700' to another format.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from  w  w  w.  j  a  va  2s  . com-->
var t = $("#date").text();
$("#sol").html(function(){
   var result = "On ";
   var sub = t.substr(0,17);
   t = t.substr(17);
   result += sub + "at ";
   var pre = t.substr(0,2);
   t = t.substr(2,3);
   var suffix = "am";
   if( parseInt(pre) > 11 ){
       suffix = "pm";
       if( pre != 12 ){
         pre = parseInt(pre) - 12;   
       }
   }
   result += pre + t + suffix;
   return result;
});
});
</script>
</head>
<body>
  <div id="date">Mon, 15 Jul 2013 09:27:39 -0700</div>
  <div id="sol"></div>
</body>
</html>

The code above is rendered as follows: