Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to add n minutes to unix timestamp

I have a unix timestamp: 1368435600. And a duration in minutes: 75 for example.

Using javascript I need to:

  1. Convert the timestamp to a string format hours:mins (09:00)
  2. Add n minutes to the timestamp: timestamp + 75mins

I tried the moment.js library:

end_time = moment(start_time).add('m', booking_service_duration);

booking_service_duration was 75 but it added an hour. I'd also rather not have to use another js library

like image 906
iamjonesy Avatar asked Apr 26 '13 15:04

iamjonesy


People also ask

How do I add 24 hours to a Unix timestamp in JavaScript?

The Unix timestamp is designed to track time as a running total of seconds from the Unix Epoch on January 1st, 1970 at UTC. To add 24 hours to a Unix timestamp we can use any of these methods: Method 1: Convert 24 hours to seconds and add the result to current Unix time. echo time() + (24*60*60);

How do you increment epoch time?

You can use the Calendar class's add method to add specify time of date from seconds, minute, hours, etc. in Calendar's constant.

How do you get Unix timestamp in seconds JavaScript?

To get the unix timestamp using JavaScript you need to use the getTime() function of the build in Date object. As this returns the number of milliseconds then we must divide the number by 1000 and round it in order to get the timestamp in seconds. Math. round(new Date().


2 Answers

Unix time is the number of seconds that have elapsed since 1 January 1970 UTC.
To move that time forward you simply add the number of seconds.

So once you have the minutes, the new timestamp is oldTime + 60*minutes
For the conversion look up parsing libraries, there is code out there for this, do some research.

like image 199
Jean-Bernard Pellerin Avatar answered Nov 01 '22 20:11

Jean-Bernard Pellerin


To add 75 minutes, just multiply by 60 to get the number of seconds, and add that to the timestamp:

timestamp += 75 * 60

To convert to hours:mins you will have to do a bit more math:

var hours = Math.floor(timestamp/60/60),
    mins = Math.floor((timestamp - hours * 60 * 60) / 60),
    output = hours%24+":"+mins;
like image 42
nullability Avatar answered Nov 01 '22 20:11

nullability