strtotime function doesnot support a specific date format - php

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
* */

Related

Date format not working correctly

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));

php date issue when converting using strtotime, but how to do this properly?

Using the following code to try and get 'Y-m-d', and should return 2016-05-10, but it is instead returning 2016-10-05.
// m-d-Y (Month-Day-Year)
$test_date = '05-10-2016';
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date;
How do I get 'Y-m-d' returned? Not trying to use explode('-', $test_date). Is this possible to do using proper time functions?
Yes, use DateTime object for this:
$test_date = '05-10-2016';
$DateTime = DateTime::createFromFormat('m-d-Y', $test_date, new DateTimeZone('utc'));
var_dump($DateTime);
OUTPUT
object(DateTime)[8]
public 'date' => string '2016-05-10 15:08:53.000000' (length=26)
public 'timezone_type' => int 2
public 'timezone' => string 'UTC' (length=3)
So
echo $DateTime->format('Y-m-d'); //2016-05-10
Note: Be aware of dates 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 dates or date_create_from_format() when possible.
Source: w3schools
You have to convert '-' by '/'.
<?php// m-d-Y (Month-Day-Year)
$test_date = str_replace('-', '/', '05-10-2016');
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date; // 2016-05-10
strtotime assume European formatted dates if they are seperated by - and USA date format if they are seperated by /
Note: from the manual 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 you can just str_replace the - for /
// m-d-Y (Month-Day-Year)
$test_date = '05-10-2016';
$test_date = str_replace('-', '/', $test_date);
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date;
Or better still use the DateTime object

How to convert date to different format

I have a biometric device which gives date format in d/m/Y h:i:s but I want to convert the same information to Y-m-d.
$var = d/m/Y h:i:s ;
echo convert($var); // Output want: Y-m-d
But if date is 10-11-2015 then how php will know that the format is d-m-y or m-d-y ?
I know how to convert yyyy-mm-dd to dd-mm-yyyy, but want dd-mm-yyyy to yyyy-mm-dd
How Can I do that ?
use the DateTime class
$date = DateTime::createFromFormat('d/m/y', '28/11/15');
echo $date->format('Y-m-d');
outputs
2015-11-28
Or you could do it on one line if you like that sort of thing:
echo \DateTime::createFromFormat('d/m/y', '28/11/15')->format('Y-m-d');
also read the note from here manual
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.
Try this:
$var = date('d/m/Y h:i:s');
$datetime = explode(' ', $var);
$date_string = implode('-', array_reverse(explode('/', $datetime[0])));
$time_string = $datetime[1];
$formated = date('Y-m-d', strtotime("{$date_string} {$time_string}"));
echo "<pre>";
print_r($formated); // test output
echo "</pre>";

strtotime returning false date

I have a problem with strtotime function in php, i'm trying to convert mm-dd-yyyy to yyyy-mm-dd. The date is entered on the text box and on submit it should save the date to the database. the problem is it returns a wrong date(1970-01-01) each time,which means my code isn't taking the variable i use to store the date, My code is:
//dateconvert
$submitdate = date($_POST['date']);
$date = date("Y-m-d", strtotime($submitdate));
//storeindb
$query ="INSERT INTO ticket SET date = '$date'";
$result = mysql_query($query);
I'm a newbie,please help.
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.
http://php.net/manual/en/function.strtotime.php
You need to use the forward slash separator for mm/dd/yyyy formats.
Use the code as:
$submitdate = $_POST['date'];
$date = date("Y-m-d", strtotime($submitdate));
Hope this hepls.
date format in $submitdate is incorrect Because the format yyyy/mm/dd should be yyyy-mm-dd so you will need to replace your / characters.
Try this:
$submitdate = str_replace("/","-",$_POST['date']);
echo date('Y-m-d', strtotime($submitdate));

Converting string to Date and DateTime

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')));

Categories