How do I convert PHP+Mysql datetime to of UNIX timestamps and format dates

  • 2020-05-17 05:00:52
  • OfStack

Written PHP + MySQL programmers know time difference, UNIX timestamp and format the date is two time representation, we often deal with Unix timestamp stored, easy processing, but not intuitive, formatting date intuitive, but processing as well as Unix timestamp freely, so sometimes need to convert each other, mutual conversion transformation ways is given below.

1. Do it in MySQL

This method is transformed in MySQL query statements. The advantage is that it does not take up the parsing time of PHP parser, which is fast. The disadvantage is that it can only be used in database queries, which has limitations.

1. UNIX time stamp converted to date function: FROM_UNIXTIME()

1 general form: select FROM_UNIXTIME(1156219870);

2. Date conversion to UNIX time stamp function: UNIX_TIMESTAMP()

1 general form: Select UNIX_TIMESTAMP('2006-11-04 12:23:00 ');

Example: the number of records mysql queried on the day:

$sql= "select * from message Where DATE_FORMAT(FROM_UNIXTIME(chattime),'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d') order by id desc";

Of course, you can also choose to convert in PHP, so let's talk about converting in PHP.

2. Done in PHP

This method completes the transformation in the PHP program, the advantage is that the data can be transformed whether or not the query in the database, the transformation range is not limited, the disadvantage is that the PHP parser takes up the parsing time, the speed is relatively slow.

1. UNIX time stamp converted to date with function: date()

1 general form: date(' Y-m-d H:i:s', 1156219870);

2. Date conversion to UNIX time stamp function: strtotime()

1 general form: strtotime('2010-03-24 08:15:42');

Related articles: