MChan
MChan

Reputation: 7192

Verify and convert input string to new Date object

I have an input field where date 'should' be entered in format (11/19/2014 6:20 PM), is there a way I can verify that date is entered in this specific format, without any extra text / numbers then convert the entered and verified date to a new Date() object? Thanks

Upvotes: 1

Views: 58

Answers (2)

jyrkim
jyrkim

Reputation: 2869

I played around with RegEx a bit and came up with following. Basically, the code test just test that the date is in certain format.

var date1 = "11/12/2014 6:20 PM";
var res1 = date1 + " --> " + (TestFormat(date1)  ? "true" : "false");
$("#results").append(res1 + "<br>");

var date2 = "811/12/2014 6:20 PM";
var res2 = date2 + " --> " + (TestFormat(date2)  ? "true" : "false");
$("#results").append(res2 + "<br>");

var date3 = "11.12/2014 6:20 PM";
var res3 = date3 + " --> " + (TestFormat(date3)  ? "true" : "false");
$("#results").append(res3 + "<br>");


function TestFormat(date) {
   return date.match(/\b[0-9]{1,2}[/][0-9]{1,2}[/][0-9]{4}[ ][0-9]{1,2}[:][0-9]{1,2}[ ]?(PM)|(AM)\b/g);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"> </div>

Upvotes: 0

Chris
Chris

Reputation: 2806

Something like this would do the trick. Basically, take advantage of Date.parse, if the result is NaN then it didn't parse successfully.

function getDate(dateString){
    var date = Date.parse(dateString);   
    if(isNaN(date)) return null;
    return new Date(date);
}

alert(getDate('11/19/2014 6:20 PM'));
alert(getDate('11/35/2014 6:20 PM'));
alert(getDate('11/19/2014 6:20 PM hello'));
alert(getDate('11/19/2014 6:20 PM 12345'));

Upvotes: 3

Related Questions