If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime in the format of YYYY-mm-dd? The only reason I ask for both Date and DateTime is because I need one in one spot, and the other in a different spot.
Use strtotime() on your first date then date('Y-m-d') to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:
Dates in the m/d/y or d-m-y formats
are disambiguated by looking at the
separator between the various
components: if the separator is a
slash (/), then the American m/d/y is
assumed; whereas if the separator is a
dash (-) or a dot (.), then the
European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
That way you are not at the whims of a certain interpretation.
To parse the date, you should use:
DateTime::createFromFormat();
Ex:
$dateDE = "16/10/2013";
$dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
However, careful, because this will crash with:
PHP Fatal error: Call to a member function format() on a non-object
You actually need to check that the formatting went fine, first:
$dateDE = "16/10/2013";
$dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
if (!$dateObj)
{
throw new \UnexpectedValueException("Could not parse the date: $date");
}
$dateUS = $dateObj->format("m/d/Y");
Now instead of crashing, you will get an exception, which you can catch, propagate, etc.
$dateDE has the wrong format, it should be "16.10.2013";
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
Since no one mentioned this, here's another way:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
To create a date from any string you can use:
$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00');
echo $date->format('Y-m-d H:i');
If you have the date formatted as "07/May/2018" and need to make it into "2018-05-07" so that it is MySQL compatible, you can use:
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
For first Date
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
For New Date
$_newDate = date("Y-m-d",strtotime($_yourDateString));
If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed.
So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.
$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600
I try all the above answers, but fail for me where in my case I built a function that get date string with the following format 'YYYY/mm/dd' . so i think much better to explode the string like that:
$old_date = explode('/', $coming_date_str);
$new_data = $old_date[0].'-'.$old_date[1].'-'.$old_date[2]; // this to convert the string as all the above posts and complete
$new_date = date('Y-m-d', strtotime($new_data));
$new_date = DateTime::createFromFormat("Y-m-d", new_date);
It worked for me to do something like:
$stringDate = "2022-02-24T17:15:00";
(if you only send the date "2022-02-24" it fills the time in 00:00:00).
$dateFormat = new DateTime($miStringDate);
If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
Or, you can make a function to accept m-d-Y and output Y-m-d:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* #see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* #param string $d various representations of date
* #return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>
If you want to get the last day of the current month you can do it with the following code.
$last_day_this_month = date('F jS Y', strtotime(date('F t Y')));
Related
I am trying to add 1 day to a date using strtotime but I canĀ“t get it to work. It always returns 02/01/1970
$date = date ("d/m/Y H:i:s", filemtime($directory));
$newdate = date("d/m/Y", strtotime($date));
$tomorrow = date('d/m/Y',strtotime($newdate . "+1 days"));
echo $tomorrow; //Always return 02/01/1970
Because strtotime() differentiates between USA date format and Sensible date format by looking at the date seperator all you need to do is us the - seperator if you want to use the sensible date format, like this, in your intermediate date manipulations
$date = date ("d-m-Y H:i:s", filemtime($directory));
$newdate = date("d-m-Y", strtotime($date));
$tomorrow = date('d/m/Y',strtotime($newdate . "+1 days"));
echo $tomorrow; //Always return 02/01/1970
FROM the manual
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Better work with DateTime():
$date = new DateTime(strtotime(filemtime($directory)));
echo $newdate = $date->format('d/m/Y');
$date->modify('+1 day');
echo $tomorrow = $date->format('d/m/Y');
Output:
20/01/2020
21/01/2020
If your filemtime($directory) returns a string formatted as your date() mask, I mean d/m/Y H:i:s, then you can do next steps:
for example, according to this mask, it looks like:
$s = "02/06/2019 22:23:22";
now you can do strtotime()
$date = date ("d/m/Y H:i:s", strtotime($s));
then transform it to the DateTime object
$st_date = new DateTime($date);
now you can simply modify it as you want
$st_date->modify('+1 days');
to see the result string value use:
$tomorrow = $st_date->format('d/m/Y');
echo 'tomorrow -> '.$tomorrow;
Output:
date->02/06/2019 22:23:22
tomorrow -> 03/06/2019
Demo
Im submitting a form that has a date range picker in it.
I have the code to get the value of the picker from the form, which is in this format:
01/03/2017 - 01/03/2017
I also have it so that it splits the date range into two variables.
$one = 20/01/2017
$two = 13/03/2017
Im now trying to format the date of these variables into the one that MYSQL uses.
My problem is that the end date will fail and be displayed as 1970-01-01 all the time.
// Get the range from the form
$daterange = $_POST["daterange"];
// Split the range into a start and end date
list($one, $two) = explode("-", "$daterange", 2);
// Test the split worked
echo $one;
echo $two;
// Format the start date into MySQL style
$StartDate = date("Y-m-d", strtotime($one));
// Test date
echo $StartDate;
// Format the end date into MySQL style
$EndDate = date("Y-m-d", strtotime($two));
//Test date
echo $EndDate;
Personnaly, I prefer the date_create_from_format that does not presume anything.
One-liner :
$StartDate = date_create_from_format( "d/m/Y" , $one )->format("Y-m-d");
Try this:
$one = '20/01/2017';
$one = str_replace('/', '-', $one);
echo date('Y-m-d', strtotime($one));
// Output: 2017-01-20
Working Code
For the reason, see The PHP Manual for strtotime() Specifically this note
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Use this to format your date:
$StartDate = date_format(date_create_from_format('d/m/Y', $one), 'Y-m-d');
To reverse:
$reverse = date('d/m/Y', strtotime($StartDate));
I am writing below code to convert the data to Date.
$date = strtotime($request->input('DueDate'));
$Job->DueDate = date('Y-m-d', $date);
$Job->save();
But this saves the data as 0000-00-00
Try this maybe: (createFromFormat's first argument should be the format which is being received by the user)
$dt = \DateTime::createFromFormat('m/d/Y', strtotime($request->input('DueDate')));
$Job->DueDate = $dt->format('Y-m-d');
$Job->save();
Cheers,,
Let say your DueDate is correctly return the data. Try this:
$date = Carbon::parse($request->input('DueDate'))->format('Y-m-d');
$Job->DueDate = $date;
$Job->save();
Use carbon instance. For more docs Carbon
From the PHP manual for strtotime()
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
So the simplest mod for your situation would be to just convert the slashes to hyphens like this
$fixDate = str_replace('/', '-', $request->input('DueDate'));
$date = strtotime($fixDate);
$Job->DueDate = date('Y-m-d', $date);
$Job->save();
I have a date in a string format such as string(10) "30/08/2014" and i need to add a year to it. In my case i'll have 30/08/2015 I was trying to use something like this but i am failing...
$start = new DateTime($details['start_date']);
$start->add(new DateInterval('P1Y'));
$end_date = $start;
any suggestion please? thank you!
The error i get now is "DateTime::__construct(): Failed to parse time string (30/08/2014) at position 0 (3): Unexpected character"
Do I have to format the string such as Y-m-d or there is a fastest and more efficient way?
This might do the trick for you.
$end_date = strtotime(date($details['start_date'])." + 1 year");
strtotime function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp.
Yes you can add one year to that date. Example:
// you have to define the format of the date that you're feeding
$start = DateTime::createFromFormat('d/m/Y', '30/08/2014'); // create format first ($details['start_date'])
// then use the method ->add() and feed it with a DateInterval Object with the proper interval
$start->add(new DateInterval('P1Y')); // add the year
$end = $start->format('d/m/Y'); // assign it to a variable
echo $end; // 30/08/2015
convert date in Y-m-d format
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
$new_date = date('Y-m-d', strtotime("+1 year", strtotime($date)));
As, PHP doesn't work well with dd/mm/yyyy format.
I hope this will help you.
$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime("+1 year", strtotime($date)));
Result:
2010-05-25
The strtotime documentation reads:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator
between the various components: if the separator is a slash (/), then the
American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.),
then the European d-m-y format is assumed.
I am using strtotime function with a specific date format but it's not working yet.
$gDate='30/04/2014';
echo strtotime($gDate);
And thats the reason you should use DateTime class in PHP
strtotime() returns long UNIX timestamp, in DateTime its getTimestamp()
$gDate='30/04/2014';
$date = DateTime::createFromFormat('d/m/Y', $gDate);
echo $date->getTimestamp();
date in your format
$gDate='30/04/2014';
change date format for make it usable by strtotime function
$date = date_create_from_format('d/m/Y', $gDate);
echo forate to check the really format
echo $mydate = date_format($date, 'Y-m-d');
strtotime function on your given date
echo $mystr = strtotime($mydate);
/*-strtotime is only works on "Y-m-d" format
*
* -in the m/d/y or d-m-y formats;
* -if the separator is a slash (/), then the American m/d/y is assumed
* -If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed
*
*
* -To avoid potential errors, you should YYYY-MM-DD
* */