Viewed   96 times

Say I have a string coming in, "2007-02-28", what's the simplest code I could write to turn that into "2007-03-01"? Right now I'm just using strtotime(), then adding 24*60*60, then using date(), but just wondering if there is a cleaner, simpler, or more clever way of doing it.



A clean way is to use strtotime()

$date = strtotime("+1 day", strtotime("2007-02-28"));
echo date("Y-m-d", $date);

Will give you the 2007-03-01

Wednesday, November 2, 2022

As far as I'm aware, there's no guaranteed way of working backwards. The best way might be to try to match regular expressions against expected well-known formats (e.g. d{2,4}[-/]d{2}[-/]d{2} for "Y-m-d") but I can't think of an easy way to do the matching without using regular expressions. You would also have to check that the parsed format makes sense, and you can't do much about ambiguous dates like 2nd of March 2009, which could be represented as 09/03/02, 2009-03-02, 02/03/09, 03/02/09, or even 09/02/03.

Sunday, December 25, 2022

var d = new Date();
d.setDate(d.getDate() - 1);

Thursday, December 1, 2022

You can use the DateTime class of PHP

  // current date
  $now = new DateTime();

  //your date
  $date = DateTime::createFromFormat('mdY', '01142012');

  // calculate difference 
  $diff = $now->diff($date);


  // output the date in format you want
  echo $date->format('d/m/Y');

EDIT: I just realized, that your format isn't one supported by php. So you have to use alternate objectbuild.

Monday, September 5, 2022
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)

To run this on a column, replace GetDate() with your column name.

The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.

Sunday, September 25, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :