Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  13] [ 5]  / answers: 1 / hits: 116897  / 11 Years ago, wed, may 22, 2013, 12:00:00

I've been looking for a while to get yesterday's date in format DD/MM/YYYY.
Here's my current code:



var $today = new Date();
var $dd = $today.getDate();
var $mm = $today.getMonth()+1; //January is 0!

var $yyyy = $today.getFullYear();
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;


With this, I get today's date in format DD/MM/YYYY (thanks SO).
But when I try this:



var $yesterday = $today.getDate()-1;


as recommended on this site somewhere else (lost the link), I get an error saying that getDate() was not found for this object.



I'm using my script with Sahi, but I don't think it's linked, as Sahi has no trouble with Javascript.



Thank you in advance.


More From » date

 Answers
20

The problem here seems to be that you're reassigning $today by assigning a string to it:



$today = $dd+'/'+$mm+'/'+$yyyy;


Strings don't have getDate.



Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:



$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.


Then just apply the formatting code you wrote:



var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;


Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.


[#78096] Monday, May 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jordenfabiand

Total Points: 678
Total Questions: 107
Total Answers: 95

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;