Tag Archives: date

PHP: How to Convert a Date/Time from UTC to another Time Zone Programming 27 MAR 2015

Having previously shown you a useful way of quickly converting a timestamp into a formatted date string, here’s a quick way of actually getting a date/time in a time zone that you actually want – and again we turn to the powerfull PHP DateTime class to do this for us.

//here we'll use a UTC (time zone independent) time for our example
//(remember, time() always returns a UTC timestamp)
$dateTimeEnd = new DateTime('@' . time());
echo $dateTimeEnd->format('Y-m-d H:i:s');            
//now let's change to GMT+2 (SAST - South African Standard Time)
$dateTimeEnd->setTimezone(new DateTimeZone('Africa/Johannesburg'));
echo $dateTimeEnd->format('Y-m-d H:i:s');

As you can see, the setTimezone function of the DateTime class does all the heavy lifting for us, making it a snap to convert timestamps between different time zones.

Just a note, if you want to get the current time zone that your script is executing under, you can make use of date_default_timezone_get:

if (date_default_timezone_get()) {
    echo 'current time zone: ' . date_default_timezone_get() . '<br />';
}

A handy tip to remember then in other words!

world map showing time zones

Related Link: http://php.net/manual/en/class.datetime.php

How to Fix PHP Warning: “It is not Safe to rely on the System’s Timezone Settings” Programming 26 FEB 2013

At some point in time with the newer versions of PHP, a lot of you would see this warning spit out by your PHP installation every time you called a date related function:

“It is not safe to rely on the system’s timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘UTC’ for ‘Africa/Johannesburg’ instead”.

What it is basically telling you is that you need to explicitly set the timezone which PHP is to use, instead of just letting it run with whatever the server was using as you used to do in the past. To do this you have two choices, which if you had bothered reading the warning message, would have been given to you on a platter.

The first option you would use on a script by script basis, which of course doesn’t really make all that much sense. Basically, call the date_default_timezone_set() function and set it to a timezone string of your choice.

The second option, and the one which makes the most sense is to set the default timezone in the php.ini configuration file itself, using the date.timezone declaration. In practice:

...
date.timezone = 'Africa/Johannesburg'

Nifty.

Related Link: http://php.net/manual/en/function.date-default-timezone-set.php

PHP: How to Add Days, Months or Years to a Date Programming 14 MAY 2012

Date work is always icky, but luckily PHP has some pretty nifty functions that can pretty much do all the heavy lifting for you.

One of most commonly faced problems is how to add either a number of days, months or years to a given date, and thanks to PHP’s fantastic strtotime function and its natural language (well sort of) parsing, this becomes pretty trivial to solve.

Taken from the PHP manual: The strtotime function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

To see it in action against the current date, try running:

echo '<p>' . date('Y-m-d', strtotime('+1 day')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+2 weeks')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+3 months')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+4 years')) . '</p>';

Of course, if you want to use a different base for its calculations, you would use the function like so:

echo '<p>' . date('Y-m-d', strtotime('+1 day', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+2 weeks', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+3 months', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+4 years', strtotime('2000-12-31'))) . '</p>';

Nifty.

Related Link: http://php.net/manual/en/function.strtotime.php

WordPress PHP: Get the Month and Year of the Newest Post on Your Blog CodeUnit 02 JAN 2012

To retrieve the month and day of the newest post on your blog via PHP (which you could of course include in a function) is relatively simple – in essence all that you are doing is putting in a call for the WordPress engine to return to you the newest post in the database and then extract the relevant information from there.

The code is as follows:

//Default values for the resulting variables
$newestyear = date('Y');
$newestmonth = date('m');
            
//Calculate newest Post Date
$args = array('orderby'=>'date','order'=>'DESC','posts_per_page'=>1,'caller_get_posts'=>1);
$newestpost = get_posts($args);

//Extract the date information            
if (!empty($newestpost)){
    $newestyear = mysql2date('Y',$newestpost[0]->post_date);
    $newestmonth = mysql2date('m',$newestpost[0]->post_date);
}

//Print out the result            
echo "

The newest post of this blog appeared in the $newestmonth month of $newestyear

";

As simple as that.

WordPress PHP: Get the Month and Year of the Oldest Post on Your Blog CodeUnit 23 DEC 2011

To retrieve the month and day of the oldest post on your blog via PHP (which you could of course include in a function) is relatively simple – in essence all that you are doing is putting in a call for the WordPress engine to return to you the oldest post in the database and then extract the relevant information from there.

The code is as follows:

//Default values for the resulting variables
$oldestyear = date('Y');
$oldestmonth = date('m');
            
//Calculate Oldest Post Date
$args = array('orderby'=>'date','order'=>'ASC','posts_per_page'=>1,'caller_get_posts'=>1);
$oldestpost = get_posts($args);

//Extract the date information            
if (!empty($oldestpost)){
    $oldestyear = mysql2date('Y',$oldestpost[0]->post_date);
    $oldestmonth = mysql2date('m',$oldestpost[0]->post_date);
}

//Print out the result            
echo "

The oldest post of this blog appeared in the $oldestmonth month of $oldestyear

";

As simple as that.

JavaScript: Calculate the Number of Days in a Month CodeUnit 02 SEP 2011

A simple way to calculate how many days are in a month in Javascript is to leverage Javascript’s built in date overflow feature – basically if you give it an incorrect date it automatically adjusts it to the correct one by assuming that the overflow are days which need simply to be added to the given date.

So, given a month and a year, it is a simply matter of forcing a date to overflow by a certain amount and then by subtracting the result from that overflow amount to learn how many days are in that month.

For example, to calculate the number of days in the current month:

var time=new Date();
var numberOfDays = 32 - new Date(time.getFullYear (), time.getMonth(), 32).getDate();

Nifty.

MySQL: How add an Hour to a DateTime Column Value CodeUnit 29 AUG 2011

If you make use of a datetime column in your MySQL database to store timestamp data, here is a simple way of adding a couple of hours to your already stored value. You know, if the client suddenly decided to change time zone or something like that! ;)

UPDATE `table` SET `datetime-column` = DATE_ADD(`datetime-column`, INTERVAL 2 HOUR) WHERE `id` = 1

You can of course also minus hours by altering the above to add a negative interval:

UPDATE `table` SET `datetime-column` = DATE_ADD(`datetime-column`, INTERVAL -2 HOUR) WHERE `id` = 1

Simple and effective.

JavaScript: Calculate the Number of Days in Last Month and Set a Date Range for it CodeUnit 01 JUL 2011

A simple way to calculate how many days are in a month in Javascript is to leverage Javascript’s built in date overflow feature – basically if you give it an incorrect date it automatically adjusts it to the correct one by assuming that the overflow are days which need simply to be added to the given date.

So, given a month and a year, it is a simply matter of forcing a date to overflow by a certain amount and then by subtracting the result from that overflow amount to learn how many days are in that month.

Thus by setting the start marker to one month back in time, we can easily learn how many days were in the last month, making it a snap to provide a quick last month range pick for a calendar control.

var time=new Date();
//force the date object to last month
var currentMonth = time.getMonth();
time.setMonth(time.getMonth()-1);
while(currentMonth == time.getMonth()){
    time.setMonth(time.getMonth()-1);
}
//get the last day of last month
var lastDay = 32 - new Date(time.getFullYear (), time.getMonth(), 32).getDate();
//if we were setting a last month range for a calendar control
var monthstart = new Date(time.getFullYear (),time.getMonth(),1);
var monthend = new Date(time.getFullYear (),time.getMonth(),lastDay);

Nifty.

Ubuntu: Get Yesterday’s Date for a Bash Script CodeUnit 10 JAN 2011

Date work often plays an important part in automated bash scripts, and as such, it is pretty useful to be able to calculate yesterday’s date for your variable work.

Now we know in order to get the current date we could use this:

NOW="$(date +"%Y/%m/%d")"

Using this info, we find that it is remarkably simple to get yesterday’s date on any Linux system with:

YESTERDAY="$(date -d 'yesterday' +%Y/%m/%d)"

There are a range of other date manipulating strings available, including things like “3 days ago”, “next Monday”, “2 months”, etc, most of which can be found on the info date entry.

Nifty.