1

How can I create an array of dates with format DD-MM-YYYY from today and 1 ahead?

I guess it's something like

var dates = [];
var date = moment();

while (date <= date.clone().add(1, 'month')) {
  dates.push(date.format('DD-MM-YYYY'));
  date = date.clone().add(1, 'd');
}

but is this the best way to do it?

And how can I do the same with minutes? I want an array with ['00:00', '00:05', '00:10', ..., '23:50', '23:55'].

I guess it's something like

var minutes = [];
var time = moment('00:00', 'hh:mm');

while (time < time.clone().add(1, 'day')) {
  minutes.push(time.format('hh:mm'));
  time = time.clone().add(5, 'minutes');
}

It's not important to use moment.js for this, but I guess it's easier.

2 Answers 2

2

Since these can be general functionality, you should make them configurable.

Time Array

For Time array, i guess creating moment object and manipulating its values will be a waste of resource. You can do that with normal loops.

Non moment version

function getDoubleDigits(str) {
  return ("00" + str).slice(-2);
}

function formatTime(h, m, is24Hr) {
  var tmp = "";
  if(is24Hr){
    tmp =" " + (Math.floor(h/12) ? "p.m." : "a.m.")
    h=h%12;
  }
  return getDoubleDigits(h) + ":" + getDoubleDigits(m) + tmp;;
}

function getTimeByInterval(interval, is24HrFormat) {
  var times = []
  for (var i = 0; i < 24; i++) {
    for (var j = 0; j < 60; j += interval) {
      times.push(formatTime(i, j, is24HrFormat))
    }
  }
  return times.slice(0);
}

console.log(getTimeByInterval(5, false))
console.log(getTimeByInterval(5, true))


Date Array

Since you want dates between 2 dates with a specific interval, its better to make them configurable:

Moment version

I have made even format configurable in this version. This can be done in non-moment version as well but I guess that(how to format date in pure JS) goes out of question's scope and so not doing that.

function getDatesInrange(d1, d2, interval, format){
  var dates = [];
  while(d1.isBefore(d2)){
    dates.push(d1.format(format));
    d1.add(interval, "days");
  }
  console.log(dates)
  return dates.slice(0)
}

getDatesInrange(moment(), moment().add(1, "month"), 1, "DD-MM-YYYY")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Non Moment Version

function getDatesInrange(d1, d2, interval){
  var dates = [];
  while(+d1 < +d2){
    dates.push(formateDate(d1));
    d1.setDate(d1.getDate() + interval)
  }
  console.log(dates)
  return dates.slice(0)
}

function formateDate(date){
  return  [getDoubleDigits(date.getDate()),
          getDoubleDigits(date.getMonth() +1),
          date.getFullYear()].join('-')
}

var startDate = new Date();
var endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
getDatesInrange(startDate, endDate, 1)

function getDoubleDigits(str) {
  return ("00" + str).slice(-2);
}

Sign up to request clarification or add additional context in comments.

3 Comments

I like the simple implementation of getting time without moment, but what if I want to translate the clock to pm/am, wouldn'it it make more sense to implement it with moment from the beginning, so that I can easily format it differently?
In that case, you just have to do var _tmp = Math.floor(h/12) ? "p.m." : "a.m" and pass h%12 to formatTime function and add _tmp to return value
@Jamgreen Please check the update. I have added a flag for that as well
0

Nothing wrong with your current implementation idea (except that the current code will cause an infinite loop. The ceiling should be declared separately), but since moment.js can take objects for duration, it's also possible to create a single helper function in which the values are calculated. For some cases this may not be the most efficient way (for times without a date, this could be overkill), but it would keep it versatile. e.g. if the range should stay the same but only the format should change to include a date, only one parameter would have to be changed.

The example below uses an ES6 generator, but the same could be easily converted to return an array instead:

function* createRange(start, duration, interval, format){
	let dt= start.clone(), target = start.clone().add(duration);
  while(dt < target){
  	yield dt.format(format);
    dt.add(interval || {years:1});
  }
}

let dates = createRange(moment(),{month:1}, {days:1}, 'DD-MM-YYYY'),
	times= createRange(moment('00:00','HH:mm'),{days:1},{minutes:5}, 'HH:mm');
  
console.log([...dates]);
console.log([...times]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Of course if certain ranges, such as the month from now, are recurring, they can be put in a separate function which calls the range function.

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.