woooow woooow - 5 months ago 20
PHP Question

Php function - How can I change any date format in a particular format (including unix timestamp format)?

a few days ago I asked for a solution that would allow me to get a particular date format, starting from any other date format. The solution that I'm using is marked as the best answer in this post.
By using this solution I have not encountered problems, but I find myself today to cope with another little problem. In practice, I also need to convert the format date unix timestamp (in milliseconds) in the format 'Y-m-d'. I tried several solutions but I have problems if I try to combine them with this function:

function change_date_format($x) {
$date = new DateTime($x);
return $date->format('Y-m-d');
}


I trust in your help,
thank you so much

Answer

Reading the DateTime object documentation would help you

function change_date_format_from_unix_timestamp($x) {
    // convert from milliseconds to seconds
    $x = floor($x / 1000);
    // convert timestamp to DateTime object
    $date = DateTime::createFromFormat('U', $x);
    // return formatted date
    return $date->format('Y-m-d');
}
Comments