This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 1 year ago.
I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.
How is this possible?
Use strtotime() and date():
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
(See the strtotime and date documentation on the PHP site.)
Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format :-)
If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');
Or, equivalently:
$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');
You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.
Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:
<?php
$source = '2012-07-31';
$date = new DateTime($source);
echo $date->format('d.m.Y'); // 31.07.2012
echo $date->format('d-m-Y'); // 31-07-2012
?>
Use:
implode('-', array_reverse(explode('-', $date)));
Without the date conversion overhead, I am not sure it'll matter much.
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);
This code works for every date format.
You can change the order of replacement variables such $3-$1-$2 due to your old date format.
$timestamp = strtotime(your date variable);
$new_date = date('d-m-Y', $timestamp);
For more, see the documentation for strtotime.
Or even shorter:
$new_date = date('d-m-Y', strtotime(your date variable));
Also another obscure possibility:
$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];
I don't know if I would use it but still :)
There are two ways to implement this:
1.
$date = strtotime(date);
$new_date = date('d-m-Y', $date);
2.
$cls_date = new DateTime($date);
echo $cls_date->format('d-m-Y');
Note: Because this post's answer sometimes gets upvoted, I came back
here to kindly ask people not to upvote it anymore. My answer is
ancient, not technically correct, and there are several better
approaches right here. I'm only keeping it here for historical
purposes.
Although the documentation poorly describes the strtotime function,
#rjmunro correctly addressed the issue in his comment: it's in ISO
format date "YYYY-MM-DD".
Also, even though my Date_Converter function might still work, I'd
like to warn that there may be imprecise statements below, so please
do disregard them.
The most voted answer is actually incorrect!
The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".
That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.
I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.
function Date_Converter($date, $locale = "br") {
# Exception
if (is_null($date))
$date = date("m/d/Y H:i:s");
# Let's go ahead and get a string date in case we've
# been given a Unix Time Stamp
if ($locale == "unix")
$date = date("m/d/Y H:i:s", $date);
# Separate Date from Time
$date = explode(" ", $date);
if ($locale == "br") {
# Separate d/m/Y from Date
$date[0] = explode("/", $date[0]);
# Rearrange Date into m/d/Y
$date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
}
# Return date in all formats
# US
$Return["datetime"]["us"] = implode(" ", $date);
$Return["date"]["us"] = $date[0];
# Universal
$Return["time"] = $date[1];
$Return["unix_datetime"] = strtotime($Return["datetime"]["us"]);
$Return["unix_date"] = strtotime($Return["date"]["us"]);
$Return["getdate"] = getdate($Return["unix_datetime"]);
# BR
$Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
$Return["date"]["br"] = date("d/m/Y", $Return["unix_date"]);
# Return
return $Return;
} # End Function
You can try the strftime() function. Simple example: strftime($time, '%d %m %Y');
Given below is PHP code to generate tomorrow's date using mktime() and change its format to dd/mm/yyyy format and then print it using echo.
$tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);
Use this function to convert from any format to any format
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
In PHP any date can be converted into the required date format using different scenarios for example to change any date format into
Day, Date Month Year
$newdate = date("D, d M Y", strtotime($date));
It will show date in the following very well format
Mon, 16 Nov 2020
date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));
function dateFormat($date)
{
$m = preg_replace('/[^0-9]/', '', $date);
if (preg_match_all('/\d{2}+/', $m, $r)) {
$r = reset($r);
if (count($r) == 4) {
if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
}
$y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
}
}
var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31
For this specific conversion we can also use a format string.
$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));
Obviously this won't work for many other date format conversions, but since we're just rearranging substrings in this case, this is another possible way to do it.
Simple way Use strtotime() and date():
$original_dateTime = "2019-05-11 17:02:07"; #This may be database datetime
$newDate = date("d-m-Y", strtotime($original_dateTime));
With time
$newDate = date("d-m-Y h:i:s a", strtotime($original_dateTime));
You can change the format using the date() and the strtotime().
$date = '9/18/2019';
echo date('d-m-y',strtotime($date));
Result:
18-09-19
We can change the format by changing the ( d-m-y ).
Use date_create and date_format
Try this.
function formatDate($input, $output){
$inputdate = date_create($input);
$output = date_format($inputdate, $output);
return $output;
}
1.2 and need to convert a date from dd/mm/yyyy to yyyy-mm-dd
For example if the date is in format 07/08/2014, it should appear as 2014-08-07
How can this be done? I know strtotime returns unix timestamp but it doesn't seem to work with dates with Slashes (/) in it. SInce I'm using 5.1, a lot of DateTime functions are not supported in it.
Please help.
Use DateTime class, strtotime function would create issue when date less then 1901 with PHP 5.3.0
Try this way
$date = DateTime::createFromFormat('d/m/Y', "07/08/2014");
$new_date_format = $date->format('Y-m-d');
Need to pass a correct format with -(date string separation with dash) in date() try
$d = str_replace('/', '-','07/08/2014');
echo date('Y-m-d', strtotime($d)); //2014-08-07
with DateTime
$objDateTime = new DateTime($d);
echo $objDateTime->format('Y-m-d'); //2014-08-07
You can do it by date('Y-m-d',strtotime($date))
Where $date is in any format that you want to convert to YYYY-MM-DD format.
By using date() function yuo can try this
echo date('Y-d-m',strtotime('07/08/2014'));
Check the documentation for more
Method : 1 demo
$date1 = "07/08/2014";
$arr = explode("/", $date1);
$date2 = $arr[2]."-".$arr[1]."-".$arr[0];
echo $date2;
Method : 2 demo
$date1 = "07/08/2014";
list($day, $month, $year) = explode("/", $date1);
$date2 = $year."-".$month."-".$day;
echo $date2;
Method 3 : with strtotime Demo
$date1 = "07/08/2014";
$date1 = str_replace("/", "-", $date1);
$date2 = date('Y-m-d', strtotime($date1));
echo $date2;
I have this date in php: 31/01/2013
I'm trying to convert it using the strtotime function like so
date("Y-m-d", strtotime(31/01/2013));
but it keeps displaying as 1970-01-01. Any know why this is?
you should include it inside a string, not a continuous series of dividing numbers
date("Y-m-d", strtotime("31/01/2013"));
This will work
$date = str_replace("/", "-", "31/01/2013");
echo date("Y-m-d", strtotime($date));
Try this
$date = "31/01/2013";
$date = date("Y-m-d", strtotime($date));
Hope it will help
Try this
$date = "01/08/2013";
echo date('Y-m-d', $date);
I have several dates being outputted into variables. They are formatted as follows:
/Date(1341788400000+0100)/
How would I go about formatting them using PHP into:
DD/MM/YYYY HH:MM
Thanks!
I ended up using the following, as the initial format was in milliseconds:
$date = 1341788400000+0100;
$date = ( $date / 1000 );
$date = date("d/m/Y H:m", $date);
$date = 1341788400000+0100;
echo date("Y/m/d H:m",$date);
Unless the +0100 is the actual time of the day (01:00) ?
First, you parse it, e.g. using strtok() http://php.net/manual/en/function.strtok.php
Then parse it as a number.
$seconds = intval($a)
Then format it using
date("Y/m/d H:m", $seconds)`.
In my database I have a time stamp column...which reflects a format like this: 2012-04-02 02:57:54
However I would like to separate them up into $date and $time.
After some research through the php manual...I found that date(), date_format() and strtotime() are able to help me to separate them...(not sure if I am right)
But I am not very sure of how to code it out...
In my php file...the timestamp extracted would be $row['DATETIMEAPP'].
Will
$date = strtotime('d-m-Y',$row['DATETIMEAPP']);
$time = strtotime('Gi.s',$row['DATETIMEAPP']);
or
$date = date('d-m-Y',$row['DATETIMEAPP']);
work?
Can I use date() to get the time as well??
Thanks in advance
$timestamp = strtotime($row['DATETIMEAPP']);
gives you timestamp, which then you can use date to format:
$date = date('d-m-Y', $timestamp);
$time = date('Gi.s', $timestamp);
Alternatively
list($date, $time) = explode('|', date('d-m-Y|Gi.s', $timestamp));
If you dont want to change the format of date and time from the timestamp, you can use the explode function in php
$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));
You can try this:
For Date:
$date = new DateTime($from_date);
$date = $date->format('d-m-Y');
For Time:
$time = new DateTime($from_date);
$time = $time->format('H:i:s');
$timestamp='2014-11-21 16:38:00';
list($date,$time)=explode(' ',$timestamp);
// just time
preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
Works for me:
select DATE( FROM_UNIXTIME( columnname ) ) from tablename;
If you want to use the DateTime class, you can do so like this:
$timestamp = $row['DATETIMEAPP']; // String formatted as "2012-04-02 02:57:54"
// Create DateTime object from custom timestamp
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $timestamp);
$date = $dt->format('d-m-Y'); // String variable of just the date
$time = $dt->format('H:i:s'); // String variable of just the time
And if you're concerned about using DateTime over strtotime() or date(), I'd like to point you in the direction of this conversation on StackOverflow titled "DateTime class vs. native PHP date-functions."
Optionally you can use database function for date/time formatting. For example in MySQL query use:
SELECT DATE_FORMAT(DATETIMEAPP,'%d-%m-%Y') AS date, DATE_FORMT(DATETIMEAPP,'%H:%i:%s') AS time FROM yourtable
I think that over databases provides solutions for date formatting too