Last active
March 20, 2019 22:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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