combobulateDateTime

Puts a date and time together, handling 12-hour clock and returns the entire thing as a valid Date/Time

by robhortn

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

JavaScript

function combobulateDateTime(sdate, stime) { 
  var isPm = false;
  
  if (!stringValid(sdate)) return 'Invalid Date';
  if (!stringValid(stime)) return 'Invalid Date';
  
  if (stime.indexOf('pm') > -1) {
    isPm = true;
  }
  stime = stime.replace('am', '');
  stime = stime.replace('pm', '');
    
  var combobulated = new Date(sdate + ' ' + stime);
  
  if (isPm) {
  	combobulated.setHours(combobulated.getHours()+12);
  }
  
  return combobulated;
  
}

function stringValid(str) {
  if (str === null) return false;
  if (typeof (str) === 'undefined') return false;
  if (str === '') return false;
  return true;
}

console.log(moment().format());

document.write('in the AM: ' + combobulateDateTime('5/9/2017', '11:30am')  + '<br/>');
document.write('in the PM: ' + combobulateDateTime('5/9/2017', '4:30pm') + '<br/>');

document.write('<hr/>');
document.write('With a blank date: ' + combobulateDateTime('', '2:30pm') + '<br/>');
document.write('With a blank time: ' + combobulateDateTime('5/9/2017', '') + '<br/>');
document.write('With a null date: ' + combobulateDateTime(null, '2:30pm') + '<br/>');
document.write('With an undefined time: ' + combobulateDateTime('5/9/2017', undefined) + '<br/>');