SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Backwards date problems

    Hi,

    I'm using the following to get the current date

    $day = date('j');
    $month = date('M');

    Which gives the day as a number without leading zeros and gives the month as as 3 letters (Jan, Feb etc).

    When I want to get a previous date I do $day = date('j')-1; to get the date yesterday. This works fine if I am not going back to before the end of the month, however it fails if I go back to the previous month. Is there a way to get the date('j')-whatever and date('M')-whatever to work even if it means changing months?

    So for example, if I was in Jan and I did date('M')-2 it would show Nov, or if it was the 1st of Jan and I did date('j')-3 it would return 29.

    Thanks!

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Your current solution wont work if it was the first of the first of the month, or even January which I think you have just discovered.

    Take a look at the following:-
    PHP Code:
    <?php
    echo date('j'strtotime('-1 Day'time())); #9
    echo date('M'strtotime('-1 Month'time())); #Dec
    ?>
    Here's a second example for clarity:-
    PHP Code:
    <?php
    $iTimestamp 
    time(); #now
    echo date('r'strtotime('-1 Day'$iTimestamp)); #Fri, 09 Jan 2009 15:53:29 +0000
    echo date('r'strtotime('-1 Month'$iTimestamp)); #Wed, 10 Dec 2008 15:53:29 +0000 
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great, thats just what I needed.

    Thanks.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •