Last active
August 4, 2020 13:18
-
-
Save calvinchoy/5191741 to your computer and use it in GitHub Desktop.
PHP create and modify date
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 | |
//create and modifying dates month | |
//creating new current date | |
$date_from = date('Y-m-01'); //first day of the current month | |
$date_to = date('Y-m-t'); //last day of the current month using t, use d for | |
//creating previous month date | |
$date_from_prev = date('Y-m-01', strtotime("first day of last month")); | |
$date_to_prev = date('Y-m-t', strtotime("last day of last month")); | |
//creating next month date | |
$date_from_next = date('Y-m-01', strtotime("first day of next month")); | |
$date_to_next = date('Y-m-t', strtotime("last day of next month")); | |
//easy acces to month info | |
$dateArray = getdate(strtotime($date_to)); | |
echo $dateArray['year'] . "<br />"; //year in 4 digit format | |
echo sprintf("%02d", $dateArray['mon']) . "<br />"; //month number in 0N format | |
echo $dateArray['mon'] . "<br />"; //month number | |
echo $dateArray['month'] . "<br />"; //month name | |
echo $dateArray['mday'] . "<br />"; //number of days in monh | |
//current date | |
$month = date("F", strtotime($date_from)); //get the month name from date object | |
// ******************************************* | |
// Modifying DateTime | |
// ******************************************* | |
$date = new DateTime($datestring); //create date from string | |
//get previous month | |
$date->modify('-1 month'); //have some problems with months with 31 days?? | |
$date->modify('last day of last month'); // this one is safe to use | |
//get next month | |
$date->modify('+1 month'); //have some problems with months with 31 days?? | |
$date->modify('last day of next month'); // this one is safe to use | |
// ******************************************* | |
// Basic date paring and localization | |
// ******************************************* | |
$dbdate = \DateTime::createFromFormat('Y-m-d H:i:s', "date string from db"); | |
$format_date = $dbdate->format('d F Y'); | |
setlocale(LC_TIME, "nl_NL"); //only necessary if the locale isn't already set | |
$format_date_localization = strftime("%d %B %Y", $dbdate->getTimestamp()) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment