PHP strtotime cheatsheet

August 18th, 2012 by Alex Leave a reply »

I think there just has to be a cheatsheet for the magic time-saving PHP strtotime function.

First to know – strtotime uses the current timezone settings, so maybe before manipulating with dates and times let’s set it to UTC and revert back when done with calculating.

// get current timezone to restore after conversions
$timezone = date_default_timezone_get();
// set current timezone to Universal Time Clock - meaning no GMT+/- offsets

Now we are ready for some testing, for convenience i’ve made a variable so that we can put any value into it, like the value from the database:

$time = time();

Alright, now we are ready for conversion of the given time. All the values returned are in a Unix Timestamp format – meaning seconds since Unix epoch.

This year start

$this_year_start = strtotime(date('Y-1-1 00:00:00', $time));

Previous year start

$prev_year_start = strtotime('-1 year', strtotime(date('Y-1-1 00:00:00', $time)));

Next year start

$next_year_start = strtotime('+1 year', strtotime(date('Y-1-1 00:00:00', $time)));

First day of current month

$first_day_of_month = strtotime(date('Y-m-1 00:00:00', $time));

Last day of current month

$last_day_of_month = strtotime('+1 month -1 day', strtotime(date('Y-m-1 00:00:00', $time)));

First day of next month

$first_day_of_next_month = strtotime('+1 month', strtotime(date('Y-m-1 00:00:00', $time)));

First day of previous month

$first_day_of_prev_month = strtotime('-1 month', strtotime(date('Y-m-1 00:00:00', $time)));

Previous Monday

$last_week_monday = strtotime('last Monday', $time);

Next Monday

$next_week_monday = strtotime('this Monday', $time);

Current day start

$this_day_start = strtotime(date('Y-m-d 00:00:00', $time));

Current hour start

$this_hour_start = strtotime(date('Y-m-d H:00:00', $time));

Next day start

$next_day_start = strtotime(date('Y-m-d 00:00:00', $time))+86400;

Next hour start

$next_hour_start = strtotime(date('Y-m-d H:00:00', $time))+3600;

Now just revert the timezone back:

// revert changes back

This page can be found by searching for:

php strtotimestrtotime() php

Comments are closed.