Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date format like "Y-m-d H:i:s" from a php date

Does someone know a way to get a string from a date that contains the format of the date?

<?php
    $date = date ("2009-10-16 21:30:45");

    // smething like this?
    print date_format ($date);
?>

I ask this because I'd like to optimize this function I've written, usually to get the date with a different timezone from a server, without doing particular things

<?php
function get_timezone_offset ($timezone, $date = null, $format = null, $offset_timezone = null) {
    if ($date == null) $date = date ($format);
    if ($offset_timezone == null) $offset_timezone = date_default_timezone_get ();
    if ($format == null) $format = "Y-m-d H:i:s";
    // I'd like to find a way that can avoid me to write $format and get it directly from the date i pass, but I don't know a particular method can do it
    // if ($format == null) $format = date_format ($date);

    $date_time = new DateTime ($date, new DateTimeZone ($offset_timezone));
    $date_time->setTimeZone (new DateTimeZone ($timezone));
    return $date_time->format ($format);
}

print get_timezone_offset ("Europe/Rome");
print get_timezone_offset ("Europe/Rome", date ("Y-m-d H:i:s"));
print get_timezone_offset ("Europe/Rome", date ("Y-m-d H:i:s"), "Y-m-d H:i:s");
print get_timezone_offset ("Europe/Rome", "2009-10-16 21:30:45", "Y-m-d H:i:s", "America/New_York");
?>

I hope to avoid regular expressions for performance reasons, but I don't know if this is possible

like image 530
vitto Avatar asked Dec 06 '09 12:12

vitto


People also ask

How can I get dd-mm-yyyy format in PHP?

Use strtotime() and date() : $originalDate = "2010-03-21"; $newDate = date("d-m-Y", strtotime($originalDate));

How can I get current date in YMD in PHP?

date('Y-m-d H:i:s') . See the manual for more. Show activity on this post. date("Y-m-d H:i:s"); // This should do it.

What is h'i s time format?

H - 24-hour format of an hour (00 to 23) h - 12-hour format of an hour with leading zeros (01 to 12) i - Minutes with leading zeros (00 to 59) s - Seconds with leading zeros (00 to 59)

How convert date format from DD-MM-YYYY to Yyyymmdd in PHP?

Change DD-MM-YYYY to YYYY-MM-DD In the below example, we have date 17-07-2012 in DD-MM-YYYY format, and we will convert this to 2012-07-17 (YYYY-MM-DD) format. $orgDate = "17-07-2012"; $newDate = date("Y-m-d", strtotime($orgDate)); echo "New date format is: ".


1 Answers

You can convert string date to timestamp with strtotime and do with the timestamp what ever you want. ;)

<?php
$date = "2009-10-16 21:30:45";
$ts   = strtotime($date);
echo date('Y-m-d', $ts);
?>
like image 185
hsz Avatar answered Sep 20 '22 20:09

hsz