Question

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

Était-ce utile?

La 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

Autres conseils

Your problem is that you're parsing the input in your locale timezone, but outputting the ISO string in UTC time. If the input is UTC as well, you need to use Date.UTC:

function myFunction1() {
    var val1="2013-08-08 14:30:59";
    var t = val1.split(/[- :]/);
    alert(t);
    var d = Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
    d = new Date(d + (30 * 60000));
    alert("toISOString" in d ? d.toISOString() : ISODateString(d));
    //     if available then use native method
}
var date = new Date('2013-08-08 14:30:59');
var hours = ((date.getHours() + 11) % 12 + 1);
var minutes = date.getMinutes();

console.log(hours+':'+minutes);

fiddle: http://jsfiddle.net/N5LDB/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top