Yogendra
Yogendra

Reputation: 1300

convert date in time and add 30 minutes in it using javascript

I am working on a project in which I have to split all date in array. so I get the time in hours and minutes variable. Time is like '2015-11-07E05:02:50.631Z'.

var res = ev_time.split("E");
var t=res[1].split(":");
var time1 =t[0] + ":" + t[1];
alert(time1);
var time2=time1.setMinutes(time1.getMinutes() + 30);
alert(time2);

when I Ignore last 2 line get correct result but when I using them I don't get the result. I want to add 30 minutes in time so I need to do that. How it will be possible?

Upvotes: 1

Views: 92

Answers (2)

Selvakumar Ponnusamy
Selvakumar Ponnusamy

Reputation: 5533

Here either time1 or time2 are not date objects and you can't access time1.getMinutes or setMintutes. You need to parse it to Date object before accessing these methods. If you just need to get desired output below code would be enough without any additional library.

var ev_time='2015-11-07E05:02:50.631Z';
var res = ev_time.split("E");
var t=res[1].split(":");
var time1 =t[0] + ":" + t[1];
console.log(time1);

var time2 = new Date();
time2.setHours(t[0],t[1]);
time2.setMinutes(time2.getMinutes() + 30);
console.log(addZero(time2.getHours())+":"+addZero(time2.getMinutes()));

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

Upvotes: 1

Saransh Kataria
Saransh Kataria

Reputation: 1497

You don't need

 time2=time1.setMinutes(time1.getMinutes() + 30);

time1.setMinutes() sets the value on time1, so if you do

time1.setMinutes(time1.getMinutes() + 30);
alert(time1)

You'll get the result

Upvotes: 1

Related Questions