Getting Date and Time Elements

Using the current DateTime
  $MyString = "This current DateTime: " . date('Y-m-d H:i:s');
  
  $TheHourNow = intval(date("H"));
Using a DateTime variable
  $ModifiedDateTime = date('Y-m-d H:i:s', strtotime($MyDateTime));

  //"Y-m-d H:i:s' gives "2000-01-01 00:00:00"

  $Year = intval(date('Y', strtotime($MyDateTime)));
  $Month = intval(date('n', strtotime($MyDateTime)));
  $DayOfMonth = intval(date('j', strtotime($MyDateTime)));
  $Hour = intval(date('G', strtotime($MyDateTime)));

Parameters you can use

Calculations

Date in # days time
  $project_end_date = date("Y-m-d", mktime(date('H'),date('i'),date('s'), date('m'),date('d') + 30,date('Y')));

Compare Date Time

     $now = strtotime(date("Y-m-d H:i:s"));
     $end = strtotime($UpgradesValidUntil);
     if ($now > $end)
     {
     }


     if ( strtotime($MyDateTimeString1) > strtotime($MyDateTimeString2) )
     {
     }

Adjusting Date Time Values

  $AdjustedTime = date('Y-m-d H:i:s',strtotime('+1 hour +30 minutes +45 seconds',strtotime($MyDateTime)));

  $AdjustedTime = date('Y-m-d H:i:s',strtotime('+1 hour',strtotime($MyDateTime)));

  $AdjustedTime = date('Y-m-d H:i:s',strtotime('-1 hour',strtotime($MyDateTime)));

  $AdjustedTime = date('Y-m-d H:i:s',strtotime("-$MyVariable minutes",strtotime($MyDateTime)));
  $MyDateTimeString = "2015/03/02";  
  $MyDateTime = strtotime($MyDateTimeString);
  $MyDateTime = strtotime("+7 day", $MyDateTime);

Values:

  • week
  • day
  • hour
  • minute
  • second

MYSQL Date & Time

To set a DateTime field to now use:

Now()

(Don’t add single quotes around it)

Is String A DateTime?

  if (strtotime($CreatedDateTime) !== FALSE)    //Returns timestamp on success, false otherwise
    //Yes string is a date

//Or, assign the value:
  if ( ($CreatedDateTime = strtotime($CreatedDateTime)) === False )
  {
    //An error occured
  }

Convert DateTime

See Strings-Values

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *