Created
April 20, 2017 17:10
-
-
Save Itach1Uchixa/ac4bf426214f7aa2e909ee5456460d06 to your computer and use it in GitHub Desktop.
Create date time with weekday placeholder
This file contains hidden or 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 | |
/** | |
* Create date time with weekday placeholder | |
* | |
* @param string $format | |
* @param string $time | |
* @param null|DateTime $timezone | |
* @return bool|DateTime | |
*/ | |
function date_create_from_format_with_w($format, $time, DateTime $timezone = null) { | |
$datetime = DateTime::createFromFormat($format, $time, $timezone); | |
// no need to continue there is no weekday | |
if ($datetime) { | |
return $datetime; | |
} | |
// if we there it means that either something is wrong or there is weekday placeholder | |
// week id in format string | |
$id = 'w'; | |
// week format for date format | |
$vDate = '?'; | |
// escape | |
$dateString = str_replace($id, $vDate, $format); | |
$datetime = DateTime::createFromFormat($dateString, $time, $timezone); | |
if (!$datetime) { | |
return false; | |
} | |
$given = str_split($time); | |
$gened = str_split($datetime->format($format)); | |
$weekDay = ''; | |
// difference will be the weekday | |
foreach ($gened as $key => $char) { | |
if ($char !== $given[$key]) { | |
$weekDay .= $given[$key]; | |
} | |
} | |
if (isset($weekDay)) { | |
$datetime->setDate( | |
$datetime->format('Y'), | |
$datetime->format('m'), | |
$datetime->format('d') + $weekDay - $datetime->format('w') | |
); | |
} | |
return $datetime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment