If you are new to PHP and want to work with Unix time, this article will guide you through the basics. We will explore how to get the current Unix timestamp, how to convert a date and/or time into a Unix timestamp, and how to convert a Unix timestamp into a date-time string.
Getting the current Unix timestamp
To get the current Unix timestamp in PHP, use the time()
function. This function returns the current Unix timestamp as an integer. You can assign this value to a variable for later use. Here’s how you can do it:
php
$unixtime = time();
Note that you don’t need to pass any parameters to the time()
function. It will automatically return the current time based on the system clock.
Converting a date and/or time into a Unix timestamp
PHP provides a built-in function called strtotime()
to convert a textual datetime string into a Unix timestamp. Here’s how you can use it:
php
$date_to_unixtime = strtotime('25th October 2009 11:12:34 PM (UTC)');
If strtotime()
fails to understand your input, it will return either -1
or false
. Also, keep in mind that PHP5 is much better at understanding dates than previous versions.
strtotime()
can also accept relative dates as well. For example, you can pass a string like „last thursday“ or „+1 year 2 months 3 weeks 4 days seconds“ to strtotime()
and it will calculate the Unix timestamp based on that relative time.
Converting a Unix timestamp into a date-time string
You can convert a Unix timestamp into a date-time string using the date()
function. This function takes two parameters: the format of the date-time string you want to generate and the Unix timestamp you want to convert.
Here’s how you can use date()
:
php
$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);
If you don’t include the second parameter (the Unix timestamp), PHP will assume you want to use the current time.
You can experiment with different format options using the UnixTime.info converter, which provides a handy list of PHP time format symbols.
Mastering Unix Time in PHP
By mastering the time()
, strtotime()
, and date()
functions, you can easily manipulate Unix timestamps and date-time strings in your PHP code. With these tools at your disposal, you can build powerful web applications that work with time-based data. Happy coding!