{"id":323,"date":"2013-05-01T07:30:49","date_gmt":"2013-05-01T11:30:49","guid":{"rendered":"http:\/\/www.johnconde.net\/blog\/?p=323"},"modified":"2023-01-08T12:08:52","modified_gmt":"2023-01-08T16:08:52","slug":"working-with-dates-and-times-in-php","status":"publish","type":"post","link":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/working-with-dates-and-times-in-php\/","title":{"rendered":"Working With Dates and Times in PHP"},"content":{"rendered":"<p>\n    Working with Dates and Times prior to PHP 5.2 meant using <code>date()<\/code>, <code>strtotime()<\/code>, and other date related functions sometimes in convoluted ways to get to the date(s) you were looking for. Fortunately with PHP 5.2 the <code>DateTime()<\/code> class were introduced. (<code>DateTimeZone()<\/code> was introduced as well but is not covered here). It was further enhanced in PHP with additionally methods as well as the new <code>DatePeriod()<\/code> and <code>DateInterval()<\/code> classes.\n<\/p>\n<h2>\n    Getting Started<br \/>\n<\/h2>\n<p>\n    Before we get started I will link to the relevant pages in the PHP manual for the classes that we will be using here. All of these require running PHP 5.2 or newer. Make sure you check your version of PHP before using any of this code.\n<\/p>\n<ul>\n<li><a href=\"http:\/\/www.php.net\/manual\/en\/class.datetime.php\" rel=\"external\">DateTime Class<\/a><\/li>\n<li><a href=\"http:\/\/www.php.net\/manual\/en\/class.dateperiod.php\" rel=\"external\">DatePeriod Class<\/a><\/li>\n<li><a href=\"http:\/\/www.php.net\/manual\/en\/class.dateinterval.php\" rel=\"external\">DateInterval Class<\/a><\/li>\n<\/ul>\n<p>\n    Also, keep in mind that when using <code>DateTime()<\/code>, when passing a Unix Timestamp as a parameter requires prepending an <code>@<\/code> to the timestamp for it be recognized as a timestamp.\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime('@123457890');\r\n<\/pre>\n<h3>\n    Getting the difference between two dates<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime1 = new DateTime();\r\n$datetime2 = new DateTime('2013-01-03 17:13:00');\r\n$interval  = $datetime1->diff($datetime2);\r\n$elapsed   = $interval->format('%y years, %m months, %d days, \r\n                                %h hours, %i minutes, %S seconds');\r\necho $elapsed;\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/DDgid\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    If you want to eliminate any periods that have zero values you can use the snippet below to remove them.\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$elapsed = $interval->format('%y years, %m months, %d days, \r\n                              %h hours, %i minutes');\r\n$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', \r\n                            ' 0 hours,', ' 0 minutes,'), '', $elapsed);\r\n$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', \r\n                             ' 1 hours, ', ' 1 minutes'), array('1 year, ', \r\n                             '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), \r\n                       $elapsed);\r\necho $elapsed;\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/ve0Wr\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Birthdays\/calculate age<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$today     = new DateTime();\r\n$birthdate = new DateTime(\"1973-04-18\");\r\n$interval  = $today->diff($birthdate);\r\necho $interval->format('%y years');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/quJ0M\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Adding period of time to a date<br \/>\n<\/h3>\n<p>\n    For PHP 5.3 or newer\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime();\r\n$datetime->add(new DateInterval('P6M'));\r\necho $datetime->format('Y-m-d');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/hKGpY\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    For PHP 5.2\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime();\r\n$datetime->modify('+6 months');\r\necho $datetime->format('Y-m-d');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/MZGKB\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Start date for a given week<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$start_date  = new DateTime(\"2013-05-13\");\r\n$day_of_week = $start_date->format(\"w\");\r\n$start_date->modify('-' . $day_of_week . ' day');\r\necho $start_date->format('l, F jS, Y');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/deS80\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Looping through the days between two dates<br \/>\n<\/h3>\n<p>\n    For PHP 5.3 or newer\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$start    = new DateTime('2013-02-01');\r\n$end      = new DateTime('2013-02-17');\r\n$interval = new DateInterval('P1D');\r\n$period   = new DatePeriod($start, $interval, $end);\r\n\r\nforeach ($period as $dt)\r\n{\r\n    echo $dt->format(\"l Y-m-d\") . PHP_EOL;\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/e7d7e\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    An alternative way to do this using <code>DateInterval::createFromDateString()<\/code>\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$start    = new DateTime('2013-02-01');\r\n$end      = new DateTime('2013-02-17');\r\n$interval = DateInterval::createFromDateString('1 day');\r\n$period   = new DatePeriod($start, $interval, $end);\r\n\r\nforeach ($period as $dt)\r\n{\r\n    echo $dt->format(\"l Y-m-d\") . PHP_EOL;\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/pST1L\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    For PHP 5.2\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$start = new DateTime('2013-02-01');\r\n$end   = new DateTime('2013-02-17');\r\nwhile ($start < = $end)\r\n{\r\n    echo $start->format(\"m\/d\/Y\") . PHP_EOL;\r\n    $start->modify(\"+1 day\");\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/soS0E\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    List all days in a month<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$start    = new DateTime('first day of this month');\r\n$end      = new DateTime('first day of next month');\r\n$interval = DateInterval::createFromDateString('1 day');\r\n$period   = new DatePeriod($start, $interval, $end);\r\n\r\nforeach ($period as $dt)\r\n{\r\n    echo $dt->format(\"l Y-m-d\") . PHP_EOL;\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/aWih1\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    For PHP 5.2\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$start = new DateTime('2013-01-31');\r\n$end   = new DateTime('2013-02-05');\r\nwhile($start < = $end)\r\n{\r\n    echo $start->format(\"m\/d\/Y\"). PHP_EOL;\r\n    $start->modify(\"+1 day\");\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/XjdNB\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Get first day of the month<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime('first day of this month');\r\necho $datetime->format('jS, F Y');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/3a0DH\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Get last day of the month<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime();\r\necho $datetime->format('Y-m-t');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/7rJ5R\" rel=\"external\">See it in action<\/a>\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime('last day of this month');\r\necho $datetime->format('F jS');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/v00ll\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Getting tomorrows date<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime('tomorrow');\r\necho $datetime->format('Y-m-d');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/c1ato\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    Or alternatively\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime();\r\n$datetime->add(new DateInterval(\"P1D\"));\r\necho $datetime->format('Y-m-d');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/cbvlN\" rel=\"external\">See it in action<\/a>\n<\/p>\n<p>\n    For PHP 5.2\n<\/p>\n<pre lang=\"PHP\" line=\"1\">\r\n$datetime = new DateTime();\r\n$datetime->modify('+1 day');\r\necho $datetime->format('Y-m-d');\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/HLLhu\" rel=\"external\">See it in action<\/a>\n<\/p>\n<h3>\n    Compare dates &#038; times<br \/>\n<\/h3>\n<pre lang=\"PHP\" line=\"1\">\r\n$date1 = DateTime::createFromFormat('H:i', '08:00');\r\n$date2 = new DateTime();\r\nif ($date1 > $date2)\r\n{\r\n    echo 'It is after 08:00';\r\n}\r\nelse\r\n{\r\n    echo 'It is not after 08:00';\r\n}\r\n<\/pre>\n<p>\n    <a href=\"http:\/\/3v4l.org\/1sN5T\" rel=\"external\">See it in action<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Working with Dates and Times prior to PHP 5.2 meant using <code>date()<\/code>, <code>strtotime()<\/code>, and other date related functions sometimes in convoluted ways to get to the date(s) you were looking for. Fortunately with PHP 5.2 the <code>DateTime()<\/code> class were introduced. (<code>DateTimeZone()<\/code> was introduced as well but is not covered here). It was further enhanced in PHP with additionally methods as well as the new <code>DatePeriod()<\/code> and <code>DateInterval()<\/code> classes. <a href=\"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/working-with-dates-and-times-in-php\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[16],"tags":[50],"class_list":["post-323","post","type-post","status-publish","format-standard","hentry","category-programming","tag-php"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/pwpo4-5d","jetpack_sharing_enabled":false,"_links":{"self":[{"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/posts\/323","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/comments?post=323"}],"version-history":[{"count":6,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/posts\/323\/revisions"}],"predecessor-version":[{"id":764,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/posts\/323\/revisions\/764"}],"wp:attachment":[{"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/media?parent=323"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/categories?post=323"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/website-0f9bf4a4.hpx.ppi.temporary.site\/blog\/wp-json\/wp\/v2\/tags?post=323"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}