I would like to query a column name's inputdate, type : date. When I query:
where (inputdate>='$VEStart' AND inputdate<='$VEEnd')
I got:
error : warning pg_query() query failed error invalid input syntax for date where (inputdate>='' AND inputdate<='').
But when I try to replace it:
where (inputdate>='2015-12-01' AND inputdate<='2015-12-31')
It works. I thought it was a problem with variables. so I tried to echo both variables, but they display the right values. Anything wrong here?
Just to give you an example beyond the comment, use something like this and ensure that you add improvements to the below code before putting it into production use; also test it well.
<?php
$VEStart = '2015-01-01';
$VEEnd = '2015-2-28';
// validate the dates
if (!isDateValid($VEStart)) {
print "Invalid start date\n";
return;
}
if (!isDateValid($VEEnd)) {
print "Invalid end date\n";
return;
}
// format the dates
$VEStart = formattedDate($VEStart);
$VEEnd = formattedDate($VEEnd);
echo sprintf ("all good - %s and %s\n", $VEStart, $VEEnd);
// see http://php.net/manual/en/function.pg-query-params.php
$sql = 'select ... where inputdate between $1 and $2';
$connection = pg_connect('...');
$result = pg_query_params($connection, $sql, array($VEStart, $VEEnd));
...more code...
// ----
// add good phpdoc
// see how others add doc - http://stackoverflow.com/questions/1904214/what-is-the-proper-php-function-documentation-format
function formattedDate($date) {
list($year, $month, $day) = explode('-', $date);
return date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
}
// add good phpdoc
function isDateValid($date) {
list($year, $month, $day) = explode('-', $date);
return checkdate($month, $day, $year);
}
?>
Related
I have a problem and don't know how to solve it. After i run the code i didn't receive corectly a period of time. I put the code here.
I think something is wrong with table from database (i use PhpMyAdmin 4.2.0 module from EasyPhp). I put an image too to see what happens. The dates marked with red need to be at the end of table.
<?php
function data_range($first, $last, $step = '+1 day', $output - format = 'd-m-Y')
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while ($current <= $last)
{
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
foreach($dates as $zile)
{
$krr = explode('-', $zile);
var_dump($krr);
$result2 = implode('/', $krr);
echo $result2 . "<br/>";
$sql4 = "INSERT INTO studenti3 (data) VALUES ('$result2')";
$rez4 = mysql_query($sql4);
}
var_dump($dates);
}
$first = "06-04-2015";
$last = "07-05-2015";
$step = "+1day";
$output_format = 'd-m-Y';
date_range($first, $last, $step, $output_format); ?>
I am trying to use perl date/time and also get file date info.
I started with this routine:
sub getTime {
#arrayDate = localtime(time);
($strSec,$strMin,$strHr,$strDate,$strMo,$strYr,$strDOW,$strDOY,$strDST) = localtime(time);
$strYr += 1900;
$strMo += 1;
if (length($strMo) < 2) { $strMo = "0" . $strMo }
if (length($strDate) < 2) { $strDate = "0" . $strDate }
if (length($strHr) < 2) { $strHr = "0" . $strHr }
if (length($strMin) < 2) { $strMin = "0" . $strMin }
if (length($strSec) < 2) { $strSec = "0" . $strSec }
$strDateTime = "$strYr$strMo$strDate $strHr:$strMin:$strSec";
}
Which worked fine.
Then I needed to get file date info using $file1date = ctime(stat($flatFile1)->mtime);.
Here is where the confusion begins. If I add use File::stat and use Time::localtime to get the file date to work, the first routine stops working and gives me this as output: 1900010 0:0:Time::tm=ARRAY(0x9a7b98)
So in order to get both to work I had to change the date routine to this:
sub getTime {
$strMon = localtime->mon();
$strMday = localtime->mday();
$strYear = localtime->year();
$strHour = localtime->hour();
$strMin = localtime->min();
$strSec = localtime->sec();
$strYear += 1900;
$strMon += 1;
if (length($strMon) < 2) { $strMon = "0" . $strMon }
if (length($strMday) < 2) { $strMday = "0" . $strMday }
if (length($strHour) < 2) { $strHour = "0" . $strHour }
if (length($strMin) < 2) { $strMin = "0" . $strMin }
if (length($strSec) < 2) { $strSec = "0" . $strSec }
$strDateTime = "$strYear$strMon$strMday $strHour:$strMin:$strSec";
}
... which I'm sure is not efficient. What's the right way to do this?
I'd like to advise you to use Time::Piece.
The above core module alters the behavior of localtime to return an object of type Time::Piece that has a strftime function. The following are your two goals performed with this module:
use strict;
use warnings;
use Time::Piece;
use File::stat;
print "Current time: " . localtime->strftime("%Y%m%d %H:%M:%S") . "\n";
print "Script created: " . localtime(stat($0)->ctime)->strftime("%Y%m%d %H:%M:%S") . "\n";
Outputs:
Current time: 20140624 19:18:17
Script created: 20140624 15:54:36
I wouldn't say that there's anything wrong with the second method. My only suggestion would be to use sprintf to format $strDateTime instead of a block of if statements:
sub getTime {
$strDateTime = sprintf("%04d%02d%02d %02d:%02d:%02d",
localtime->year() + 1900,
localtime->mon() + 1,
localtime->mday(),
localtime->hour(),
localtime->min(),
localtime->sec());
}
For reference: the field %04d means a decimal (d) field of length 4, padded with 0. Using fixed-length, padded decimal fields is a quick and easy way to format numbers.
You can see the whole guide on sprintf in the documentation.
I've following code to compare two dates in PHP,which one while be appropriate method
<?php
$var = date('d-m-Y',strtotime('29-05-2012'));
$var1 = date('d-m-Y',strtotime('27-06-2012'));
echo $var; //29-05-2012
echo $var1; //27-06-2012
if($var1 >= $var) //method 1
{
echo 'var1 is future date';
}
if(strtotime($var1) >= strtotime($var)) //method 2
{
echo 'var1 is future date(second if)';
}
?>
In above two methods,method-1 is not working,is it not a correct way to compare two dates in PHP ?
No, the first method is incorrect because $var1 and $var are strings, so you can't compare them like that.
However, strtotime() creates unix timestamps (integers), so you can and should compare them like that.
Just leave the date as string, and convert with strtotime in if ().
$a = '29-5-2012';
$b = '27-6-2012';
if (strtotime($a) >= strtotime($b)) {
echo "$a is future date.";
} else {
echo "$b is future date.";
}
// 27-6-2012 is future date.
Depending on you php version >= 5.3 you can try date_diff()
$time1 = strtotime('29-05-2012'); # <--- past
$time2 = strtotime('27-06-2012'); # <--- future
echo max($time1,$time2);
echo "<br />";
echo min($time1,$time2);
why not:
if (mktime(0,0,0,12,31,2012) > mktime(0,0,0,6,25,2011)) {
echo "12/31/2012 is after 6/25/2011";
}
$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));
Here is my CI form validation rule:
$datetime_string = $this->form_validation->set_rules('event_date', 'Select', 'callback_date_validate');
Here is my callback:
function date_validate($select_value)
{
$year = '';
$month = '';
$day = '';
$hour = '';
$minutes = '';
$datetime = $this->input->post('event_date');
if (strpos($datetime, ' # ') !== 'FALSE' && $datetime != '')
{
$datetime_explode = explode(' # ', $datetime);
if (strpos($datetime_explode[0], '/') !== 'FALSE' && $datetime_explode != '')
{
$date_explode = explode('/', $datetime_explode[0]);
$year = $date_explode[2];
$month = $date_explode[1];
$day = $date_explode[0];
}
if (strpos($datetime_explode[1], ':') !== 'FALSE')
{
$time_explode = explode(':', $datetime_explode[1]);
$hour = $time_explode[0];
if (strpos($time_explode[1], ' ') !== 'FALSE')
{
$minutes_explode = explode(' ', $time_explode[1]);
$minutes = $minutes_explode[0];
$am_pm = $minutes_explode[1];
if ($am_pm == 'PM' || $am_pm == 'pm')
$hour += 12;
}
}
}
$datetime_string = $year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minutes . ':00';
if (!preg_match('/^\d{4}-\d{2}-\d{2} 2[0-3]|[01][0-9]:[0-5][0-9]:[0-5][0-9]$/', $datetime_string))
{
$this->form_validation->set_message('date_validate', 'Oops');
}
else // user picked something
{
return $datetime_string;
}
}
According to the CI documentation, you can return data from a form validation callback, but by setting the rule equal to a variable, I get this error:
Object of class CI_Form_validation could not be converted to string
What am I doing wrong?
I think the problem is in this line:
$datetime = $this->input->post('event_date');
The value of event_date field is captured in a parameter of your function $select_value try using your parameter instead of post data.
$this->form_validation->set_rules(...); should be called inline and not assigned to a variable. You have assigned it to $datetime_string. Remove this assignment.
I don't know if you ever solved this but I was scratching around the documentation wondering the same thing as your question.
First of all, you just want...
$this->form_validation->set_rules('event_date', 'Select', 'callback_date_validate');
Don't assign it to a variable.
Next, you want to run your validation rules/callbacks...
if ($this->form_validation->run() == TRUE) {
// VALIDATION OK, CHECK OUR CALLBACK DATA
var_dump($this->input->post());
}
Now you should see your data returned from the callback in... $this->input->post('event_date');
The thing that confused me about returning data from callbacks was this thread on the official CI forums... http://codeigniter.com/forums/viewthread/191087/ where people are suggesting that the callback doesn't change the POSTed data. They are only partially correct. It doesn't change it under $_POST['whatever'] but it does change it in $this->input->post('whatever')
As this was the 3rd result in Google I hope this helps someone out.
I pass two Date::Manip::Date objects, perfectly valid dates to my sub:
sub get_duration {
my $duration;
my #val;
my $from = $_[0]->new_date();
my $to = $_[1]->new_date();
# $from->parse("2012-03-06");
# $to->parse("2012-03-07");
print $from . " ".$to. "<-- <br />";
my #f = $from->value();
if ($f[0] == 2012) {
$from->config("ConfigFile",$HOLIDAYS_2012);
} elsif ($f[0] == 2013) {
$from->config("ConfigFile",$HOLIDAYS_2013);
} elsif ($f[0] == 2014) {
$from->config("ConfigFile",$HOLIDAYS_2014);
} elsif ($f[0] == 2015) {
$from->config("ConfigFile",$HOLIDAYS_2015);
}
my #t = $to->value();
if ($t[0] == 2012) {
$to->config("ConfigFile",$HOLIDAYS_2012);
} elsif ($t[0] == 2013) {
$to->config("ConfigFile",$HOLIDAYS_2013);
} elsif ($t[0] == 2014) {
$to->config("ConfigFile",$HOLIDAYS_2014);
} elsif ($t[0] == 2015) {
$to->config("ConfigFile",$HOLIDAYS_2015);
}
print "from " . #f ." to ". #t."<br>";
my $delta = $from->calc($to, "business");
print $from->calc($to, "business") . " <-";
#val = $delta->value();
if ($to->is_business_day()) {
$duration = $val[3]+1;
} else {
$duration = $val[3];
}
return $duration;
}
I get the output
Date::Manip::Date=HASH(0xacdf7a0) Date::Manip::Date=HASH(0xacdfb50)<--
from 0 to 0
<-
Software error:
Can't call method "value" on an undefined value at '#val = $delta->value();'
That is the two dates are passed all right, I got NO errors when it tries to set their config files, Regardless, the value arrays #t and #f are empty and it breaks down as soon as I try to get the delta.
However if I uncomment the two lines
$from->parse("2012-03-06");
$to->parse("2012-03-07");
(hence ignoring the parameters)
It works just fine as intended.
There's something I'm missing about passing objects in Perl I suspect?
Firstly
&get_overlap_duration($saved[$i][5], $saved[$i][6], $saved[$i][7], $saved[$i][8])
Is called
I've printed the #saved values and they're correct, they're strings:
2012-03-06, 2012-03-08, 2012-03-05, 2012-03-07
Then inside get_overlap_duration those strings are
my $from1 = new Date::Manip::Date;
my $to1 = new Date::Manip::Date;
my $from2 = new Date::Manip::Date;
my $to2 = new Date::Manip::Date;
$from1->parse($_[0]);
$to1->parse($_[1]);
$from2->parse($_[2]);
$to2->parse($_[3]);
Then there's there is a call for get_duration for instance $duration = get_duration($from2, $to1);
I've checked the server error log there were no complaints apart from the software error displayed in the browser.
The problem is that on the following line:
my $delta = $from->calc($to, "business");
It's not returning a valid object. Which likely means that something in the calc() function is failing. Since "business" is not a valid date. And if you read the Date::Manip::Calc man page, the mode parameter is only legal when you pass in two date objects before that and you've only passed one.