JsLearner JsLearner - 6 months ago 34
jQuery Question

JavaScript/jQuery - Convert from 24 Hr Datetime String to 12Hr Date format?

var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";

this.outDate = function()
{
return getJustTime(startDateTime,timeZone);
}

function getJustTime(startDateTime,timeZone)
{
outDt = new Date(startDateTime.replace(/ /g,'T'));
return outDt;
}

**Expected Output**
this.outDate = "10.30 PM CDT";


I have two variables as above with 24 hour datetime string and i want to convert it into 12 hour format date string. What i am missing in the missing?

P.S : I can't use any datetime librarires.

Answer

Just write your own. The date object is very helpful.

function am_or_pm (date) {
    var date_obj = new Date(date);
    var hours = date_obj.getHours();
    var morn_or_night;
    // I wouldn't do this in production, but this is to make my logic really clear - I would probably use a conditional operator here. 
    // Handling Midnight
    if (hours === 0) {
        hours = 12;
        morn_or_night = 'AM';
    // Handling noon
    } else if (hours === 12) {
        morn_or_night = 'PM'
    } else if (hours > 12) {
        hours = hours - 12;
        morn_or_night = 'PM';
    } else {
        morn_or_night = 'AM';
    }
    return hours.toString()+':'+date_obj.getMinutes()+' '+morn_or_night;
}