Friday, December 19, 2014

Javascript: Convert date string to timestamp

Below is the codesnippet to convert date string to a timestamp:

var dateString = $('#dateText').val(); // in format yyyy-MM-dd HH:mm:ss
var timeStamp = convertDateStringToTimeStamp(dateString);

function convertDateStringToTimeStamp(dateString)
{
 
 var date = parseDate(dateString);
 return date.getTime();
}
 
function parseDate(dateString)
{
    var dateParts = dateString.split(' ');
    var timeParts = dateParts[1].split(':');
    
    var dateParts = dateParts[0].split('-');

    var date = new Date(dateParts[0], parseInt(dateParts[1], 10) - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
    
    return date;
}

No comments:

Post a Comment