Related
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;
}
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;
}
$date =$row2['DeliveryDate'];
$date now contains the date variable as a datetime, to display it I would use:
echo date_format($date, 'm-d-y');
the problem I'm having is extracting single values from $date for example:
$datetime = strtotime($row2['DeliveryDate']);
$mysqldate = date("d", $datetime);
returns this error:
Warning: strtotime() expects parameter 1 to be string, object given in
C:\xampp\htdocs\tutorials\DerBlatt\hebrewDateTrial.php on line 10
I've tried numerous ways to extract the day/month/year into single variables but nothing works
if someone can suggest a way it might work I'll be very greatfull;
I've copy/pasted code from many sites but all of them use an example of the date as a string, unfortunately i haven't found a solution for the datetime variable.
I wanna do something like:
$date =$row2['DeliveryDate'];
//whatever conversion code that comes in between.
$d = //the day from datetime
$m = //the month from datetime
$y = //the year from datetime
If you are using PHP 5.3 or better ,use the DateTime class .
if you want to display in this format $format='m-d-y';
Retrieving data from database .
$date =$row2['DeliveryDate'];
$date = DateTime::createFromFormat('Y-m-d H:i:s',$date);
if($date){ // if the date is correct
$yourdate = $date->format($format);
$year = $date->format('Y');
$month = $date->format('m');
$day = $date->format('d');
}
Saving to database .
$date = DateTime::createFromFormat($format,$date);
if($date){
$date = $date->format('Y-m-d H:i:s');
$row2['DeliveryDate'] = $date;
}else{
$row2['DeliveryDate'] = date('Y-m-d H:i:s');
}
Try this:
echo date('d',strtotime($row2['DeliveryDate']));
i think it will work.
so this is how i made it work (very funny)...
$m = date_format($row2['DeliveryDate'], 'm');
$d = date_format($row2['DeliveryDate'], 'd');
$y = date_format($row2['DeliveryDate'], 'y');
echo 'Month: '.$m.' Day: '.$d.' Year: '.$y;
Thank you guys for helping me, sometimes my best solution is just using my head...
I have a form in which date format is dd/mm/yyyy . For searching database , I hanverted the date format to yyyy-mm-dd . But when I echo it, it showing 1970-01-01 . The PHP code is below:
$date1 = $_REQUEST['date'];
echo date('Y-m-d', strtotime($date1));
Why is it happening? How can I format it to yyyy-mm-dd?
Replace / with -:
$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
January 1, 1970 is the so called Unix epoch. It's the date where they started counting the Unix time. If you get this date as a return value, it usually means that the conversion of your date to the Unix timestamp returned a (near-) zero result. So the date conversion doesn't succeed. Most likely because it receives a wrong input.
In other words, your strtotime($date1) returns 0, meaning that $date1 is passed in an unsupported format for the strtotime function.
$date1 = $_REQUEST['date'];
if($date1) {
$date1 = date( 'Y-m-d', strtotime($date1));
} else {
$date1 = '';
}
This will display properly when there is a valid date() in $date and display nothing if not.
Solved the issue for me.
$inputDate = '07/05/-0001';
$dateStrVal = strtotime($inputDate);
if(empty($dateStrVal))
{
echo 'Given date is wrong';
}
else{
echo 'Date is correct';
}
O/P : Given date is wrong
Another workaround:
Convert datepicker dd/mm/yyyy to yyyy-mm-dd
$startDate = trim($_POST['startDate']);
$startDateArray = explode('/',$startDate);
$mysqlStartDate = $startDateArray[2]."-".$startDateArray[1]."-".$startDateArray[0];
$startDate = $mysqlStartDate;
The issue is when your data is set to 000-00-00 or empty you must double-check and give the correct information and this issue will go away. I hope this helps.
Use below code for php 5.3+:
$date = new DateTime('1900-02-15');
echo $date->format('Y-m-d');
Use below code for php 5.2:
$date = new DateTime('1900-02-15');
echo $date->format('Y-m-d');
finally i have found a one line code to solve this problem
date('d/m/Y', strtotime(str_replace('.', '-', $row['DMT_DATE_DOCUMENT'])));
I've got a date in this format:
2009-01-01
How do I return the same date but 1 year earlier?
You can use strtotime:
$date = strtotime('2010-01-01 -1 year');
The strtotime function returns a unix timestamp, to get a formatted string you can use date:
echo date('Y-m-d', $date); // echoes '2009-01-01'
Use strtotime() function:
$time = strtotime("-1 year", time());
$date = date("Y-m-d", $time);
Using the DateTime object...
$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');
Or using now for today
$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');
an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));
this worked perfect.. hope this will help someone else too.. :)
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
// set your date here
$mydate = "2009-01-01";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastyear);
Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval to modify a \Datetime object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Which returns:
2008-01-01
For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php
You can use the following function to subtract 1 or any years from a date.
function yearstodate($years) {
$now = date("Y-m-d");
$now = explode('-', $now);
$year = $now[0];
$month = $now[1];
$day = $now[2];
$converted_year = $year - $years;
echo $now = $converted_year."-".$month."-".$day;
}
$number_to_subtract = "1";
echo yearstodate($number_to_subtract);
And looking at above examples you can also use the following
$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));