Wrong output while converting to new date format [duplicate] - php

This question already has answers here:
Strtotime() doesn't work with dd/mm/YYYY format
(17 answers)
Closed 7 years ago.
I have a string value "27/03/2015" and i want to convert this string to new date format. Below is the code i am using now.
<?php echo date("Y-m-d",strtotime("27/03/2015")); ?>
But it gives a wrong output like this 1970-01-01.

It is because strtotime isn't being able to parse your date string. Try:
<?php echo strtotime("27/03/2015"); ?>
The result should be False. Since False is the same as 0, you are really running date("Y-m-d", 0), the result of which is "1970-01-01" (the "unix epoch").
strtotime only recognizes certain date formats, listed here. The closest to your input format is "27-03-2015" ("Day, month and four digit year, with dots, tabs or dashes").

try this
<?php echo date("Y-m-d",strtotime(str_replace('/', '-', YOUR DATE )))); ?>

Here is the simple solution
$date = '27/03/2015';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));

in above case / Seperator is not valid (as the date will be evaluated to Date 3 & Month 27)
you can use -
echo date("Y-m-d",strtotime("27-03-2015"));

I guess "/" is not allowed or, should I say, unrecognizable as a parameter for strtotime.
<?php
$dateString = "27/03/2015";
//now let's check if the variable has a "/" inside of it.
//If it does, then replace "/" with "-".
//If it doesnt, then go with it.
//"." also accepted for strtotime as well.
$dateString = (strpos($dateString,"/") ? str_replace("/","-",$dateString) : $dateString);
echo date("Y-m-d",strtotime($dateString));
?>

Related

PHP how to convert dd/mm/yy to yyyy-mm-dd [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 2 years ago.
I'm trying to convert convert dd/mm/yy to yyyy-mm-dd. After i researched several methods and I found this.
$var = '20/01/2021';
$date = str_replace('/', '-', $var);
$show_date = date('Y-m-d', strtotime($date));
It works fine with result 2021-01-20.
However, my input was two digit yy only which is 20/01/21 and the result became 2020-01-21.
With an ambigous date like you have it is better to use the DateTime class as you can set the input format. See the following example from the documentation:
$var = '20/01/21';
$date = DateTime::createFromFormat('d/m/y', $var); // "d/m/y" corresponds to the input format
echo $date->format('Y-m-d'); //outputs 2021-01-20

Converting date format m.Y into MySQL compatible Y-m-d in PHP [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 7 years ago.
I have date string like:
08.2015
What I want to do is, to convert it into MySQL compatible date format:
date("Y-m-d", strtotime(date_create_from_format('m.Y', "08.2015")));
Doesn't work as expected. What am I doing wrong?
BTW: It's okay if I'll get 2015-06-01 result.
You don't need strtotime there.
echo DateTime::createFromFormat('m.Y', "08.2015")->format("Y-m-d");
Output: 2015-08-31
Fiddle
And if you always want to get first date of month with only m.Y given, you can do
echo DateTime::createFromFormat('d.m.Y', "01."."08.2015")->format("Y-m-d");
Output: 2015-08-01
Fiddle
<?php
//explode the date
$dateProps = explode('.',"08.2015");
//prepare the format
$date = $dateProps[1].'-'.$dateProps[0].'-01';
//use date functions
$date = date('Y-m-d', strtotime($date));
Try this.
$var = '08.2015';
$date = '01-'.str_replace('.', '-', $var);
echo date('Y-m-d', strtotime($date));
I think below SQL useful to you.
SELECT DATE_FORMAT(STR_TO_DATE('06.2015','%m.%Y'),'%Y-%m');
output: 2015-06
Thank you.
First of all, if you want to use strtotime , it should be this : strtotime('01.08.2015'), that is to say , Year month day must be all needed.
You can try below sql-
SELECT DATE_FORMAT(STR_TO_DATE('08.2015','%m.%Y'),'%Y-%m-01')

date format change from string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strtotime() doesn’t work with dd/mm/YYYY format
I have this variable which i get the info like this:
echo $start=$_REQUEST['to'];
It outputs something like this:
2/04/2012
What i need is to convert it like this: 20120402
Could you please help me? I tried strotime and no success..
I tried converting the string before in a date format, then i converted it in a Ymd format, but i kept receiving a strange date, something like 1970 !
I tried this:
$time = strtotime( $date );
$myDate = date( 'y-m-d', $time );
thanks!
It may work.
<?php
$start=$_REQUEST['to'];
$date = explode("/",$start);
$size = sizeof($date);
for($i=$size;$i>=0;$i--) {
$date_get .= $date[$i];
}
echo $date_get;
?>
You should use strftime instead of date.
$myDate = strftime('%Y%m%d', $time);

Convert MMDDYYYY to date for PHP [duplicate]

This question already has answers here:
Parse and reformat a datetime string
(6 answers)
Closed 11 months ago.
I have a string with a date which is in this format MMDDYYYY (ie. 01132012, 01142012 etc.)
I need to do something on a page, if that string is 14 days or less from the current date.
ie. Today is 01132012, so any strings with 12312011 or a less date are going to be showing something on a page.
Can anyone help with this? I've tried
echo date("d/m/Y", strtotime('01142012'));
But to no avail.
You can use the DateTime class of PHP
<?
// current date
$now = new DateTime();
//your date
$date = DateTime::createFromFormat('mdY', '01142012');
// calculate difference
$diff = $now->diff($date);
...
// output the date in format you want
echo $date->format('d/m/Y');
?>
EDIT: I just realized, that your format isn't one supported by php. So you have to use alternate objectbuild.
I prefer using strptime.
<?
$dt = strptime('01142012', '%m%d%Y');
echo sprintf("%02d/%02d/%04d", $dt['tm_mday'], $dt['tm_mon']+1, $dt['tm_year']+1900);
If you use PHP 5.3 or above, you can also use date_parse_from_format()
How about some substr + mktime?
$string = '01142012';
$time = mktime(0, 0, 0,
substr($string, 0, 2),
substr($string, 2, 2),
substr($string, 4, 4)
);
echo date('d/m/Y', $time);
try date('m-d-y', strtotime('01142012'));
could also try something like;
$var = strtotime('01142012');
$var2 = date ('F j, Y', $var);
Your string input of '01142012' cannot be parsed by strtotime() as it is not a valid as it is returning -1 as an answer. To convert this into a valid date you will need to add either slashes or dashes to separate the numbers.
The easiest way would be to store the dates with the dashes or slashes, such as '01-14-2012' or '01/14/2012' in the database from now on or you are going to have to create your own function to convert the numbers into a valid form for strtotime().
To do this you could do something like this:
function makeValidDate($date) {
$valid_date = array();
$array = str_split($date); //split characters up
foreach($array as $key => $character){
if($key==2 || $key==4){
$character = '-'.$character; //add relevant formatting to date
$valid_date[] = $character; //add this to the formatted array
}
else{
$valid_date[] = $character; // if not dashes or slashes needed add to valid array
}
}
return implode($valid_date); // return the formmatted date for use with strtotime
}
You can then do this to get a valid date:
$valid_date = makeValidDate('01142012');
echo date("d/m/Y", strtotime($valid_date));
I haven't tested this but you should get a good idea of what to do.
EDIT: Capi's idea is a lot cleaner!!
try "preg_match(pattern,string on wich the pattern will be aplied)";
http://www.php.net/manual/en/function.preg-match.php
you can also define an offset. so first take te first 2 digits. than take the other 2 digits and after that get the other four digits. after that place them in one string. after that use maketime,strtotime,date. this kind of stupid solution but i only thought of that. hope this will help

strtotime() converts a non existing date to another date

I am building a timestamp from the date, month and year values entered by users.
Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012"..
I dont want this to happen..
$str = "31-02-2012";
echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012
Can anyone help? I dont want a timestamp to be returned if the date is not original.
You might look into checkdate.
That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc...
Try
$str = '31-02-2012';
echo date('d-m-Y', strtotime(str_replace('-', '/', $str)));
However 31-02-2012 is not a valid English format, it should be 02-31-2012.
If you have PHP >= 5.3, you can use createFromFormat:
$str = '31-02-2012';
$d = DateTime::createFromFormat('d-m-Y', $str);
echo $d->format('d-m-Y');
You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date.
You can workaround this behavior
<?php
$str = "31-02-2012";
$unix = strtotime($str);
echo date('d-m-Y', $unix);
if (date('d-m-Y', $unix) != $str){
echo "wrong";
}
else{
echo date("d-m-Y", $unx);
}
or just use checkdate()
Use the checkdate function.
$str = "31-02-2012";
$years = explode("-", $str);
$valid_date = checkdate($years[1], $years[0], $years[2]);
Checkdate Function - PHP Manual & Explode Function - PHP Manual
Combine date_parse and checkdate to check if it's a valid time.
<?php
date_default_timezone_set('America/Chicago');
function is_valid_date($str) {
$date = date_parse($str);
return checkdate($date['month'], $date['day'], $date['year']);
}
print is_valid_date('31-02-2012') ? 'Yes' : 'No';
print "\n";
print is_valid_date('28-02-2012') ? 'Yes' : 'No';
print "\n";
Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.

Categories