Search code examples
javascriptjquerydate-formatisodate

Need to Get the time in correct format from JavaScript to ISODateString?


Actually i am trying to convert the date from java script date to ISO date format but the time is displayed is incorrect.In this the time is 14:30 but i am getting 9:30 it should be 2:30.And i need to add 30 min to my time.This function is used to convert JavaScript date To ISO data.

function myFunction1()
{
 var val1="2013-08-08 14:30:59";
 var t = val1.split(/[- :]/);
    alert(t);
 d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
 d = new Date(d.getTime() + (30 * 60000));
 alert(ISODateString(d));
}


function ISODateString(d){
      function pad(n){return n<10 ? '0'+n : n}
      return d.getUTCFullYear()+'-'
          + pad(d.getUTCMonth()+1)+'-'
          + pad(d.getUTCDate()) +' '
          + pad(d.getUTCHours())+':'
          + pad(d.getUTCMinutes())+':'
          + pad(d.getUTCSeconds())
    }

Share with me please if you know about.I have worked jsfiddle


Solution

  • There is no need for UTC and therefore remove it.

    Basically what you're looking for is (converting to 12 hrs time format)

    pad(d.getHours() > 12 
                  ? d.getHours() - 12 : d.getHours())
    

    Complete Code:

    function ISODateString(d) {
        function pad(n) {
            return n < 10 ? '0' + n : n
        }
        return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' 
              + pad(d.getDate()) + ' ' + pad(d.getHours() > 12 
              ? d.getHours() - 12 : d.getHours()) 
              + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
    }
    

    Result:

    input: 2013-08-08 14:30:59

    output: 2013-08-08 03:00:59 //Since you increased 30 mins

    JSFiddle