Skip to content

Instantly share code, notes, and snippets.

@mooror
Last active March 20, 2019 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooror/5175c99e1dbd8d4ddf1005083031c430 to your computer and use it in GitHub Desktop.
Save mooror/5175c99e1dbd8d4ddf1005083031c430 to your computer and use it in GitHub Desktop.
PHP Code Snippet - Add hours and minutes to date time string and convert it to timestamp
<?php
///////////////////////////////////
// //
// Using DateTime Object (OOP) //
// //
///////////////////////////////////
// The original date time string
// NOTE: This is currently using the current date and time
// but you can change the variable below to any valid date time string
$dateString = 'NOW';
// Hours and minutes you would like to add to
// the date and time string.
// NOTE: Defaults to 48 hours or 2 days
$hours = 48;
$minutes = 00;
// New date time string calculation
$datetimeObject = new DateTime($dateString);
$datetimeObject->add(new DateInterval('PT'.$hours.'H'.$minutes.'M'));
// OPTIONAL - Conversion to timestamp
$timestamp = $datetimeObject->getTimestamp();
// Output for testing purposes
echo "<b>Using the DateTime Object (OOP): </b><br />";
$datetimeObject = new DateTime($dateString);
$dateString = $datetimeObject->format("Y-m-d\TH:i:s");
echo "<br />Original Date -><br />".$dateString."<br />";
$datetimeObject->add(new DateInterval('PT'.$hours.'H'.$minutes.'M'));
$newDateString = $datetimeObject->format("Y-m-d\TH:i:s");
echo "<br />New Date -><br />".$newDateString."<br />";
echo "<br />Timestamp -><br />".$timestamp."<br /><br /><br />";
///////////////////////////////////
// //
// Using the date method //
// //
///////////////////////////////////
// The original date time string
// NOTE: This is currently using the current date and time
// but you can thange the line below to any valid date time string
$dateString = date('Y-m-d\TH:i:s');
// Hours and minutes you would like to add to
// the date and time string.
// NOTE: Defaults to 48 hours or 2 days
$hours = 48;
$minutes = 00;
// New date time string calculation
$newDateString = date('Y-m-d\TH:i:s',strtotime("+$hours hour +$minutes minute",strtotime($dateString)));
// OPTIONAL - Conversion to timestamp
$dateTime = DateTime::createFromFormat("Y-m-d\TH:i:s", $newDateString);
$timestamp = $dateTime->getTimestamp();
// Output for testing purposes
echo "<b>Using the date() method: </b><br />";
echo "<br />Original Date -><br />".$dateString."<br />";
echo "<br />New Date -><br />".$newDateString."<br />";
echo "<br />Timestamp -><br />".$timestamp."<br />";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment