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.
Related
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
I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');
So I know how to format a date in PHP, but not from a custom format. I have a date that is a string "YYMMDD" and I want to make it "MMDDYYYY'. strtotime doesn't seem like it would do a good job of this when the MM and DD are both low digits.
Use str_split:
$date1 = "YYMMDD";
list($yy, $mm, $dd) = str_split($date1, 2);
// MMDDYYYY format, assuming they are all > 2000
$date2 = $mm . $dd . "20" . $yy;
If you're running PHP >= 5.3, have a look at DateTime::createFromFormat. Otherwise, if you don't want to use pure string manipulation techniques, use the more primitive strptime together with mktime to parse the time into a UNIX timestamp, which you can then format using date.
Maybe I am under-thinking this, but couldn't you just:
$oldDate='040220'; // February 20th, 2004
$year = substr($oldDate, 0,2);
$year += $year < 50 ? 2000 : 1900;
$date = preg_replace('/\d{2}(\d{2})(\d{2})/', '$1/$3/'.$year, $oldDate);
And you'd have the string you were looking for, or something close enough to it that you could modify from what I wrote here.
Have many dates prior to 1910? If not, you could check your YY for <=10, and if true, prepend "20" else prepend "19"... Kinda similar approach to MM and DD check for <10 and prepend a "0" if true... (This is all after exploding, or substring... Assign each part to its own variable, i.e. $M=$MM; $D=$DD; $Y=$YYYY; then concatenate/arrange in whatever order you want... Just another potential way to skin the proverbial cat...
Ended up doing:
$expiration_date_year = substr($matches['expiration_date'],0,2);
$expiration_date_month = substr($matches['expiration_date'],2,2);
$expiration_date_day = substr($matches['expiration_date'],4,2);
$expiration_date = date('m/d/Y', mktime(0,0,0,$expiration_date_month, $expiration_date_day, $expiration_date_year));
I have a field (nonTimeStampDate) that has date like this
2010-03-15
and I want to check it against another field (timeStampDate) which is
2010-03-15 15:07:45
to see if the date matchs. But as you can see since the format is different it doesnt match even though the date is same.
Any help will be appreciated.
thanks
My first thought is using date() and strtotime() to reformat them.
$date1 ="2010-03-15";
$date2 = "2010-03-15 15:07:45";
if (date('Y-m-d', strtotime($date1)) == date('Y-m-d', strtotime($date2)))
{
//do something
}
This would work and give you more flexibility in how the two dates formatted to begin with. Not the most elegant.
You might want to try this code:
if (strpos($date1, $date2) !== false) {
// Your code here
}
It is a bit faster than exploding the value by a space as suggested by Anax. Make sure that $date2 contains the shorter of the two dates.
If you are certain about the input string format, you need to split it and take the first part, in order to compare it with your original date:
$splits = explode(' ', $original);
$datapart = $splits[0];
if ($datepart == $nonTimeStampDate) {
// your code here
}
What Anax says, or if these values are in MySQL tables, you can use MySQLs datetime functions (like DATE()) to compare them in MySQL.
Then, just compare the date part:
<?php
if( substr('2010-03-15 15:07:45', 0, 10) == '2010-03-15' ){
echo 'Dates match';
}
?>
Whatever, if you need to do serious date handling, you need to use a proper format, such as a DateTime object.
$firstDate = date("Y-m-d", strtotime("2010-03-15"));
$secondDate = date("Y-m-d", strtotime("2010-03-15 15:07:45"));
if( $firstDate == $secondDate ) {
// true
}
I have a date in the following format
MM-DD-YYYY
How can I convert this to UNIX time in PHP
Thanks
Having a small problem
$date = strtotime($_POST['retDate']);
print $date; //Prints nothing
print $_POST['retDate']; //Prints 08-18-2009
If the format is always like that, I'd would try something like:
list($m,$d,$y) = explode('-', '08-18-2009');
$time = mktime(0, 0, 0, $m, $d, $y);
print date('m-d-Y', $time);
As for your example, the problem is the function fails. You should check it like so:
if(($time=strtotime('08-18-2009'))!==false)
{
// valid time format
}
else
echo 'You entered an invalid time format';
or you can use php date obyek to do that, like this
$tgl = "30-12-2013";
$tgl2 = DateTime::createFromFormat('d-m-Y', $tgl);
print_r($tgl2);
echo($tgl2->format('Y-m-d'));
i hope this can help...
Use strtotime:
$str = "03-31-2009";
$unixtime = strtotime($str);
Since these answers and comments were provided, PHP has updated to include a native function that suits this situation perfectly. Check out PHP's DateTime object here. This includes a createFromFormat method that will do as requested. In this particular example:
$date = DateTime::createFromFormat('j-M-Y', $_POST['retDate']);
From there, you can format it as desired or perform any other date operations:
echo $date->format('Y-m-d');
And that's it! Keep in mind that this is only provided in PHP 5.3.0 or higher!