Browse By

JavaScript: How to get the time in 12 hour format from a MySQL TimeStamp?

MySQL timestap field is in 0000-00-00 00-00-00 format. Sometime your application need only the time part with 12 hour time format. So how would you do that?

The following javascript function will let’s you pass the whole timestamp string and returns the 12 hour time with AM or PM. Pass your timestamp string at the run time of the code. So you may want to call the following function in your PHP code like the below code with mix of php and javascript code.

var timeFormat = getTimeFromString("<?php echo $timestamp; ?>");

The complete function is given below.

// format the time and return from the timestap string
function getTimeFromString(dateString){
  // format the date in javascript, get the time value only
  // Split timestamp into [ 2014-10-21 10:20:50 ]
  var dt = dateString.split(" ");
  // Apply each element to the Date function
  var ti = dt[1];
  //get the time into array
  var timeArray = ti.split(":");
  //string val for 12 hour
  var timeAMPM = '';
  //intiger val for hour
  var timeHour = 0;
  // check if time is AM or PM
  if (timeArray[0] > 12){
  	timeHour = timeArray[0] % 12;
  	timeAMPM = 'AM';
  	timeHour = timeArray[0];
  	timeAMPM = 'PM';
	//return the formated time in 12 hour format
	return(timeHour+':'+timeArray[1]+' '+timeAMPM);

I hope this method helps you somewhere in the code. If you have any questions/comments, please share in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>