I'm trying to display 9 day numbers with js.
With PHP it will look like this:
for($i = 0; $i < 4; $i++){
$date = new DateTime();
$date->sub(new DateInterval('P'.(4 - $i).'D'));
echo '<span class="day_nr">'.$date->format('d').'</span>';
}
$date = new DateTime();
echo '<span class="selected_day_nr day_nr">'.$date->format('d').'</span>';
for($i = 1; $i < 5; $i++){
$date = new DateTime();
$date->add(new DateInterval('P'.$i.'D'));
echo '<span class="day_nr">'.$date->format('d').'</span>';
}
This is what i have found in JS:
var date = new Date();
date.setDate(date.getDate() + 1); console.log(date)
But this will show the whole date like: Wed Feb 21 2018 11:23:30 GMT+0100 (CET)
How do i display it with only the day number? (21)
You can use .getDate()
to get the date of the month represented by the Date object. For example:
var date = new Date();
date.setDate(date.getDate() + 1); console.log(date.getDate())
To emulate PHP's P
option, a good starting point would be date.getTimezoneOffet()
, however this will not include proper formatting as with PHP.
For more information, take a look at the docs. You may also find this list a little more helpful.
Thank to @Toastrackenigma for (.getDate())
This is how the loop works:
//4 days back
var date = new Date();
for(i = -4; i < 0; i++){
var date = new Date();
date.setDate(date.getDate() + i);
$('.panel-body .row .cold-12').append('<span class="day_nr">'+date.getDate()+'</span>');
}
//Today
var date = new Date();
$('.panel-body .row .cold-12').append('<span class="selected_day_nr day_nr">'+date.getDate()+'</span>');
//4 days forward
var date = new Date();
for(i = 1; i < 5; i++){
var date = new Date();
date.setDate(date.getDate() + i);
$('.panel-body .row .cold-12').append('<span class="day_nr">'+date.getDate()+'</span>');
}
Console: -4 days, +4 days
As said previously by Toastrackenigma you can use: getDate () to retrieve only what you want. But for the manipulation of the dates I can advise you the awesome library : https://momentjs.com/ which is really useful.