Convert MMDDYYYY to date for PHP [duplicate] - php

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

Related

Add a space in a php string at an exact space

I have lots of date and time data which have been put together like so 05/12/2113:30
What I want to do is separate into two strings like so $date = '05/12/21' and $time = 13:30 so that I can prepare them for database entry in a correct format.
They are always the same first 8 digits (including 2 '/') are the date and the last 5 digits (including ':') are the time.
How can i go about separating them correctly using php?
Thanks so much for your help and I am sure its easy I just seem to be having a brain fart moment.
$value = "05/12/2113:30";
var_dump(substr($value, 0, 8)); //05/12/21
var_dump(substr($value, 8, 5)); //13:30
Using substr() you can extract from any place.
$string = '05/12/2113:30';
$date = substr($string, 0, 8); // 05/12/21 <-- from start
$time = substr($string, -5); // 13:30 <-- from end
You can use substr:
first substring will be date (from 0 to 8)
second substring will be time (from 8 to the end of string)
$date = substr($str,0,8);
$time = substr($str,8);
Using the builtin DateTime Object its actually quite easy when you can guarantee the input format.
$in = '05/12/2113:30';
$dt = (new DateTime())->CreateFromFormat('d/m/yG:i', $in);
echo 'database format = ' . $dt->format('Y-m-d H:i:s');
RESULT
datebase format = 2021-12-05 13:30:00

Wrong output while converting to new date format [duplicate]

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

PHP split a string after certain character, but the string length varies

I use a radio button that gives me two variables concatenated and I need to separate them later. It gives me a time and a date in a format 11:30pm3, where 3 is the date and 11:30pm is the time. I can split it fine with my function but if the time is one digit, like 7:30pm for example, it throws things off. I can use military time but that's not what I want.Is there a way to change this so it splits the string right after character "m" so it will work for am/pm, regardless of the length of the time being 7:00am or 07:00am. Thanks in advance.
$string = $Radio; //This is the value I get
$MeetTime = substr("$string", 0, 7); //Gives me 11:30am
$MeetDay = substr("$string", 7, 2); //Gives me 2
find out where the m is and do your logic on that
if m is at 6 then its a full length one
$loc = stripos($string,"m");
if its at 5 then it's short so adjust your split
if(preg_match('~^([\\d]{1,2}:[\\d]{1,2}[ap]m)([\\d]+)$~i', trim($string), $Matches)){
var_dump($Matches); // See what this prints
}
Hope it helps.
try this:
$date = '11:30am3';
$date = explode('pm', $date);
if(count($date) <= 2){
$date = explode('am', $date[0]);
}
print_r($date);
where $date[1] is the time and $day[0] the date.
But you should use somet other format, I'd recommend timestamps.

dd/mm/yyyy format, but how about d/m/yyyy format to Ymd

how can we format
12/4/2012 to 20120412
and
4/11/2012 to 20121104
or
5/4/2012 to 20120405
using php?
i have use strtotime() and
$date = new DateTime('4/11/2012');
$date = $date->format('Ymd');
but they all fail, is there a function in php that solve this? or we have to use something like regex?
If you read the documentation to strtotime(), you'll see that it makes assumptions about whether a date is in dd mm yyyy or mm dd yyyy format.
In short, the assumption changes depending on whether the string contains hyphens or slashes as the separators. Unfortunately, both hyphens and slashes are used by people writing both formats, so there are always going to be examples that are misinterpreted by strtotime().
Because of this, neither format is ideal, because of the ambiguity between the two of them. The best option is to provide the date to the program in a less ambiguous format.
You could do a string replace on the input string to set the separators to the expected format before you call strtotime(). Not a great solution, but it does work.
If you can't change the input format, and if you know for certain which format you'll be receiving, you can use the [DateTime::createFromFormat] method instead of strtotime(). This parses date strings as strtotime() does, but takes a specific format string, so you can tell it exactly what you're expecting, so removes the ambiguity.
Hope that helps.
This should work:
function x($string) {
$array = explode('/', $string);
$a = $array[0];
$b = $array[1];
$c = $array[2];
if (( (int)$a - 10) < 0) { $a = "0$a"; }
if (( (int)$b - 10) < 0) { $b = "0$a"; }
return "{$c}{$b}{$a}";
}
All of your date examples are ambiguous, and could be either DMY or MDY dates. You will need to parse the date yourself, something along the lines of
list($d, $m, $y) = explode('/', $date);
// compose your output from $d, $m and $y
$dateTime = strtotime('12/4/2012');
$output = date('Ymd',$dateTime);
http://php.net/manual/en/function.date.php

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