-2
    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.

JsLearner
  • 109
  • 1
  • 5
  • 16

2 Answers2

1

var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
var slot='AM';
var a = startDateTime.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
if(c[0]>12){
  slot='PM';
  c[0] = c[0] - 12;
}
var date = c[0]+'.'+c[1]+' '+slot+' '+timeZone ;
console.log(date);
Toney
  • 66
  • 1
  • 1
    Hi @Toney! Welcome to StackOverflow. Aside from posting a code snippet. Do explain why this answers the post. Check the [How do I write a good answer](http://stackoverflow.com/help/how-to-answer) for more tips. :) – AL. Jun 02 '16 at 01:41
1

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;
}
Paul
  • 1,056
  • 11
  • 18