Convert Datetime To TimeStamp Using PHP 7

PHP supports date functions to handle date & time to implement and provide a method to convert human-readable dates to Unix Timestamp. One of those methods is strtotime().

You can also check other recommended Date PHP tutorials,

PHP strtotime

The strtotime() function in PHP translates an English textual date-time description to a UNIX timestamp. The strtotime() function takes an English string as an argument that represents the date-time information.

Syntax

strtotime(time, now);

Whereas:
time : It specifies a date/time string.
now : It is an optional parameter.The now parameter specifies the timestamp used to calculate the returned value.

Examples:

echo strtotime("now"), "\n";
echo strtotime("11 March 2022"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+2 week"), "\n";
echo strtotime("next Friday"), "\n";
echo strtotime("last Saturday"), "\n";

Output:

1646974188 
1646956800 
1647060588 
1648183788 
1647561600 
1646438400

Get Current Date in PHP

echo date("Y-m-d", strtotime("now"));

Output:

2022-03-11

Future Date in PHP

echo date("Y-m-d", strtotime("2022-03-11 +2 month"));

Output:

2022-05-11

Past Date in PHP

echo date("Y-m-d", strtotime("2022-03-11 -2 month"));

Output:

2022-01-11

strtotime to convert English text to a date

$textDate = "11th March 2022";

echo strtotime($textDate), "\n";

echo date("Y-m-d", strtotime($textDate))."\n";

Output:

1646956800
2022-03-11

2 thoughts on “Convert Datetime To TimeStamp Using PHP 7

  1. Hi, thanks for the tip about strtorime. When adding times, what about working days instead of current days… Actually I’m using third part js add-ons (luxon). Thanks !

Leave a Reply

Your email address will not be published.