0

What is the JavaScript equivalent to the following PHP code:

$expTime = time() + (5 * 60 * 60); // now plus 5 hours (5 hour; 60 mins; 60 secs) 
$expTimeStr = gmdate('Y-m-d\TH:i:s\Z', $expTime); 

3 Answers 3

1
var expTime    = new Date((+new Date()) + (5 * 60 * 60000))
var m          = expTime.getMonth() + 1
var d          = expTime.getDate()
var y          = expTime.getFullYear()
var h          = expTime.getHours()
var i          = expTime.getMinutes()
var s          = expTime.getSeconds()
var expTimeStr = y +"-"+ m +"-"+ d +" "+ h +":"+ i +":"+ s
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't going to work. If the time is 11:00PM, then the hour will be correct, but the day display will be wrong.
fixed bluntly using gnarfs method for the +5 hours
That's a nice solution! I changed something anyways: it's weird that you don't have a leading zero for Month, Day, Minutes and Seconds (even Hours). So, to whom might be interested: var expTimeStr = y +"-"+ (m.toString().length<2 ? '0' : '')+m +"-"+ (d.toString().length<2 ? '0' : '')+d + ...
Important!! If you want the right local time offset: var expTime = new Date((+new Date()) + (new Date().getTimezoneOffset() * 60000))
1

The gmdate() function doesn't transfer well to JavaScript... There is a gmdate() port on phpjs that uses the date() function from phpjs to do the complex formatting.

To calculate the date:

var time = new Date((+new Date()) + (5 * 60 * 60000)); // js times are ms

alert(time.toUTCString()); // quick JS method to return UTC time

The (+new Date()) forces the Date() into an integer before adding ms, and passing it back to the new Date() constructor.

Comments

1

The built in date formatting for Javascript isn't incredible, but I can offer two helpful libraries to accomplish what you want. The first is something called phpjs - Javascript ports of a number of php functions.

http://phpjs.org/functions/index

http://phpjs.org/functions/gmdate:586

The second is a jQuery plugin:

http://joncom.be/code/jquery-phpdate/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.