...

View Full Version : How can I add hours to date ??



Nirbhay
05-21-2009, 06:21 AM
Hi All,

I am facing problem while adding 4 hours to date like : "25-9-2006 06:20:16"
I have tried doing like this :

var now = new Date("25-9-2006 06:20:16");
var hrs = now.getHours();
hrs += 4;
var res=now.setHours(hrs);

alert(now);

it is giving me the result in UCT format, but I want the result in this "25-9-2006 10:20:16" format.Can anyone help me out ,its urgent ...

thanx in advance ...:)

rnd me
05-21-2009, 07:57 AM
you can re-order and edit the "f(something)" lines of this:





Date.prototype.toShort= function () {
function f(n) {
return n < 10 ? "0" + n : n;
}

return ""+

f(this.getFullYear()) + "-" +
f(this.getMonth() + 1) + "-" +
f(this.getDate()) + " " +
f(this.getHours()) + ":" +
f(this.getMinutes()) + ":" +
f(this.getSeconds()) +

"";}//end Date.toShort

//example
var d=new Date;
alert(d.toShort()) // "2009-05-21 01:01:39"

Nirbhay
05-21-2009, 08:14 AM
Thanx for the reply ...

I am not getting how r u goining to call the function f and pass any value to this function ...

rnd me
05-21-2009, 08:34 AM
Thanx for the reply ...

I am not getting how r u goining to call the function f and pass any value to this function ...

you dont need to change or call anything really, i set it up so you could re-arrange the order of whole lines.


you just use it right before you need it, the above code builds it in to all dates.

the date syntax won't parse, but it's close:



var now = new Date("9/25/2006 06:20:16");
var hrs = now.getHours();
hrs += 4;
var res=now.setHours(hrs);

alert(now.toShort());

EDIT:
this might be a US-format only, not sure.
browsers parse the Date.toLocale(""|Time|Date)String() methods' formats, which vary by regional settings.

Philip M
05-21-2009, 09:18 AM
Another way (easy to adjust for any number of days/hours/mins/secs ahead):-


<script type = "text/javascript">

var z = 4; // number of hours ahead
var zz = 30; // number of minutes ahead

//var nd = new Date(); // time now

var nd = new Date("9/25/2006 22:20:16"); // USA date format
nd = nd.getTime() + (3600000 * z); // + z hours
nd = nd + (60000 * zz); // + zz minutes
var d = new Date(nd);
var mm = d.getMonth() +1;
if (mm <10) {mm = "0" + mm}
var dd = d.getDate();
if (dd <10) {dd = "0" + dd}
var yy = d.getFullYear();
var hrs = d.getHours();
if (hrs <10) {hrs = "0" + hrs}
var mns = d.getMinutes();
if (mns <10) {mns = "0" + mns}
var secs = d.getSeconds();
if (secs <10) {secs = "0" + secs}
futureDate = (dd + "-" + mm + "-" + yy + " " + hrs + ":" + mns + ":" + secs ); // UK date format
alert (futureDate)

</script>

Nirbhay
05-21-2009, 12:33 PM
thanx a lot ...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum