Reputation: 19
I want to display yesterday's date, and day.
Script for today's date:
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
// Array of month Names
var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var now = new Date();
document.write(dayNames[now.getDay()] + ", " +
monthNames[now.getMonth()] + " " +
now.getDate() + ", " + now.getFullYear());
// -->
</script>
I know that adding a -1 will change the date/year, but it doesn't successfully change the day of the week/month because we have listed the days/months in an array, so there is nothing before Sunday and nothing before January.
How can I display the date from yesterday/however days ago making sure the day and month will change?
Upvotes: 1
Views: 275
Reputation: 1759
Your best bet is to use a sane date handling library and avoid the horrid 70's-style API that JavaScript provides out-of-the-box. Save your time and sanity and use Moment.js:
// this is a quick way to load, not what I would do for production installs:
eval($.get('http://momentjs.com/downloads/moment.min.js').responseText);
document.write(moment().subtract(1, 'day').format("dddd MMMM D, YYYY"));
Note that this means you can subtract things other than days, like months or years, and it works without you having to remember the math (or DST for that matter):
console.log(moment("2008-02-29").subtract(1, 'year').format("dddd MMMM D, YYYY"))
> Wednesday February 28, 2007
console.log(moment("2008-02-29").add(4, 'years').format("dddd MMMM D, YYYY"))
> Wednesday February 29, 2012
console.log(moment("2008-02-29").add(3, 'years').format("dddd MMMM D, YYYY"))
> Monday February 28, 2011
Upvotes: 0
Reputation: 1755
you can try this: see DEMO
dayNames[now.getDay()==0?6:now.getDay()-1]
EDIT:
and for setDate to yesterday : Demo
now.setDate(now.getDate()-1); // set yesterday for now
Upvotes: 1
Reputation: 2254
Yesterday's day of the week: dayNames[(now.getDay() + 6) % 7]
(equivalent to -1 + 7
)
Last month: monthNames[(now.getMonth() + 11) % 12]
Upvotes: 0
Reputation: 413702
You can create a Date instance for yesterday:
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
You can then proceed as you're currently doing things. The JavaScript Date code will ensure that the right thing happens with all the other fields. In other words, if "today" is 1 Jan, then "yesterday" will be 31 Dec of the previous year.
Upvotes: 0