JakubKubera
JakubKubera

Reputation: 436

How to display dates as a string?

I have an array of dates.

For example:

[Date {Thu Jul 21 2016 00:00:00 GMT+0200}, null, Date {Sat Jul 23 2016 00:00:00 GMT+0200}, null, Date {Mon Jul 25 2016 00:00:00 GMT+0200}, Date {Tue Jul 26 2016 00:00:00 GMT+0200}, Date {Wed Jul 27 2016 00:00:00 GMT+0200}]

Seven date after another. Null means no active date.

I would view as:

21.07 ; 23.07 ; 25.07 - 27.07

Another example:

[Date {Thu Jul 21 2016 00:00:00 GMT+0200}, Date {Fri Jul 22 2016 00:00:00 GMT+0200}, null, Date {Sun Jul 24 2016 00:00:00 GMT+0200}, null, Date {Tue Jul 26 2016 00:00:00 GMT+0200}, Date {Wed Jul 27 2016 00:00:00 GMT+0200}]

Seven date after another. Null means no active date.

As:

21.07 - 22.07 ; 24.07 ; 26-07 - 26-07

Thank you for your help.

@edit:

21.07
null
23.07
null
25.07
26.07
27.07

21.07 ; 23.07 ; 25.07 - 27.07


21.07
null
23.07
null
25.07
null
27.07

21.07 ; 23.07 ; 25.07 ; 27.07


21.07
null
23.07
24.07
25.07
null
null

21.07 ; 23.07 - 25.07


21.07
22.07
23.07
24.07
25.07
null
27.07

21.07 - 25.07 ; 27.07

Upvotes: 1

Views: 54

Answers (2)

Arnauld
Arnauld

Reputation: 6139

Assuming that your list is always made of consecutive days, separated by one (or several) nulls, this should do what you're expecting:

var input = [
  new Date('Thu Jul 21 2016 00:00:00 GMT+0200'),
  null,
  new Date('Sat Jul 23 2016 00:00:00 GMT+0200'),
  null,
  new Date('Mon Jul 25 2016 00:00:00 GMT+0200'),
  new Date('Tue Jul 26 2016 00:00:00 GMT+0200'),
  new Date('Wed Jul 27 2016 00:00:00 GMT+0200')
];

function formatDay(d) {
  return ('0' + d.getDate()).substr(-2, 2) + '.' +
         ('0' + (d.getMonth() + 1)).substr(-2, 2);
}

var result = [], end, start = null;

input.forEach(function(v, n) {
  v && (end = v);
  !start && (start = v);
  
  if(start && (!v || n == input.length - 1)) {
    result.push(formatDay(start) + (end == start ? '' : ' - ' + formatDay(end)));
    start = null;
  }
});
result = result.join(' ; ');

console.log(result);

Upvotes: 1

black_pottery_beauty
black_pottery_beauty

Reputation: 879

To create string based of date array

<script>
var array = [];
 for (i = 0; i < 10; i++) { 
        var date = new Date();
        array.push(date);
    }

</script> 

<script>
    arr = ['Thu Jul 21 2016 00:00:00 GMT+0200', null,'Sat Jul 23 2016 00:00:00 GMT+0200', null,'Mon Jul 25 2016 00:00:00 GMT+0200','Tue Jul 26 2016 00:00:00 GMT+0200','Wed Jul 27 2016 00:00:00 GMT+0200'];


    var newarray = "";
    for (i = 0; i < arr.length; i++) { 
        if(arr[i] !=null){
        var date = new Date(arr[i]);
        newarray += (date.getDate()+'.'+date.getMonth()+';');
    }
    }
</script>

Upvotes: 0

Related Questions