0

I have two date with time:

YY:MM:DD hh:mm

This is the time period I need to calculate gap and divide it into 'n' equal parts.

In order to build a graph

Pls Help

ZPPP
  • 1,567
  • 2
  • 18
  • 27

4 Answers4

2

Because date is actually saved as an integer and only shown as

YY:MM:DD hh:mm

You can actually just take the two date variables and devide them by the n

gap = (date1 - date2)/n

and then you can get the intervals by just adding the gap multiple times

for(var i = 1; i <= n; i++){
   newDate[i] = new Date(date2 + gap*i);
}
1

something like this?

you can operate directly with dates in javascript

var date1 = new Date(2017, 01, 01, 10, 15, 00);
var date2 = new Date(2016, 12, 01, 10, 14, 45);

var dateDiff = new Date(date1-date2); //this will return timestamp 

var years = dateDiff.getFullYear() - 1970; //init date always is 1970
var months = dateDiff.getMonth();
var days = dateDiff.getDate();
var minutes = dateDiff.getMinutes();
var seconds = dateDiff.getSeconds();

alert(years + " years.\r " + 
      months + " months\r" + 
      days + " days\r" + 
      minutes + " minutes\r" + 
      seconds + " seconds");
Jordi Flores
  • 2,080
  • 10
  • 16
1

I would suggest that you try out the momentjs library. It provides powerful functionalities for you to conveniently work with date objects.

For example, given 2 string dates that are properly formatted, you can get the precise difference between the 2 times easily like so:

let time1  = moment("04/09/2013 15:00:00");
let time2 = moment("04/19/2013 18:20:30");

let diffMilliseconds = time1.diff(time2); // gives the time difference in milliseconds
let diffDays = time1.diff(time2, 'days'); // gives the time difference in days
Calvin Alvin
  • 2,448
  • 2
  • 16
  • 15
1

You can use the date object to convert the given time format to timestamp and then find difference between timestamp. For example:

var date1 = "2017-03-04 11:22:22"
var date2 = "2017-03-04 13:11:42"

var timestamp1 = Date.parse(date1, "YYYY-MM-DD HH:mm:ss")
var timestamp2 = Date.parse(date2, "YYYY-MM-DD HH:mm:ss")

var difference = timestamp2 - timestamp1;

console.log(difference) //in milliseconds

Now you can divide the difference in to n parts and add to timestamp1 to get following timestamp based on difference/n interval.

Apoorv Joshi
  • 389
  • 3
  • 15