Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to date in PHP and format to YYYYMMDD [duplicate]

Tags:

php

datetime

I want to convert date from, for example, 1441065600 to YYYYMMDD format. How do I do that?

$temp = date("Y-m-d",1441065600);
$rel_date = date_format( $temp, "YYYYMMDD");

The code above gives an error:

date_format() expects parameter 1 to be DateTimeInterface

like image 379
tonywei Avatar asked Nov 07 '25 17:11

tonywei


1 Answers

Using date()

Simply write:

<?php

echo date('Ymd', 1441065600);

Otherwise, using a DateTime instance:

Short

<?php

echo (new DateTime())->setTimestamp(1441065600)->format('Ymd');

Note: the setTimestamp() method do not takes a string as parameter! Otherwise, you may want to do so:

Long

<?php

$english = '1441065600';
$timestamp = strtotime($english);
$date = new DateTime($timestamp);
echo $date->format('Ymd'); // 20161214

Descriptions

strtotime() - Parse about any English textual datetime description into a Unix timestamp

DateTime - Representation of date and time

Note: I created a new DateTime instance from the UNIX timestamp, English textual representation may lead to an error.

Other formats

I recommend you to read the DateTime::format() method documentation along with the date() function documentation to learn more about date formats.

like image 58
Alexandre Avatar answered Nov 10 '25 08:11

Alexandre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!