Friday, May 30, 2014

Formatted String to JS Date


From this snippet, decided to use the same inspiration to demo my date conversion function I wrote. It converts dd-MMM-yyyy String to a javascript date:


<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>

 

   ddMMyyyyToJsDate = function(input){

// with ddMMMyyyy passed of  '30-May-2014'
var parts = input.match(/^(\d\d)-(\w{3})-(\d{4})$/);
                // parts[0] is '30-May-2014' , parts[1] is 30 , parts[2] is 'May' , parts[3] is 2014 ,
if((parts == null) ||(parts.length != 4)){
return "Invalid Date";
}
//  converts 'May' to 4
var MMM = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(parts[2]) / 3  ;
//  verify year of 2014 is 4 digits
if(parts[3].length != 4){
return "Invalid Date";
}
// verify  day is between 1 and 31
if((parts[1] < 1) || (parts[1] > 31)){
return "Invalid Date";
}  
 
// pass in 2014, 4, 30
return new Date(parts[3], MMM , parts[1]); // months are 0-based
}

x = ddMMyyyyToJsDate ('30-May-2014') ;


elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

var ddMMyyyyToJsDate ; // Declare converter

</script>

</body>
</html>

No comments:

Post a Comment