problems getting values from query string - php

My below function that is copied from another function that works fine. Should get values from the query string and turn them into a date:
function updateShift()
{
echo $name = $_GET['shift_name'];
echo $start_date = date('Y-m-d H:i:s', strtotime("{$_GET['start_hours']}:{$_GET['start_minutes']} {$_GET['start_ampm']}"));
echo $stop_date = date('Y-m-d H:i:s', strtotime("{$_GET['stop_hours']}:{$_GET['stop_minutes']} {$_GET['stop_ampm']}"));
}
However it returns:
Shift Name
1969-12-31 17:00:00
1969-12-31 17:00:00
Any idea why this works fine elsewhere but not here? The query string is there as evidenced by the shift_name coming through correctly.

What if you do this:
function updateShift()
{
echo $name = $_GET['shift_name'];
echo $start_date = date('Y-m-d H:i:s', strtotime($_GET['start_hours'].':'.$_GET['start_minutes'].' '.$_GET['start_ampm']));
echo $stop_date = date('Y-m-d H:i:s', strtotime($_GET['stop_hours'].':'.$_GET['stop_minutes'].' '.$_GET['stop_ampm']));
}
or
function updateShift()
{
echo $_GET['shift_name'];
echo date('Y-m-d H:i:s', strtotime($_GET['start_hours'].':'.$_GET['start_minutes'].' '.$_GET['start_ampm']));
echo date('Y-m-d H:i:s', strtotime($_GET['stop_hours'].':'.$_GET['stop_minutes'].' '.$_GET['stop_ampm']));
}

The dates you received were the start of the Unix epoch since your date function call was getting false (or 0) as the second argument. I just ran some quick tests using your code and I am seeing that strtotime is returning false with the values supplied.
echo "{$_GET['start_hours']}:{$_GET['start_minutes']} {$_GET['start_ampm']}";
=> '4:0 PM'
You need to make sure you have 2 digits in your minutes field to allow strtotime to see it as a valid time and to parse it correctly. To to this you can either update your query string, use str_pad or sprintf to ensure you have the 2 digits required for the time to be valid.

Related

If a Date exist return a calculated date

I have the code below to add days to a date.
$date = '[[lbc_dates_lbc_date]]';
$date = date('d F y', strtotime('+28 days', strtotime($date)));
echo $date;
This works perfectly for cases where a date entry actually exists, however, it's displaying an odd date for cases where date entry doesn't exist yet (blank).
Can you amend the code to say if a date exists add days, otherwise leave blank?
Please see image attached (errors in red, correct view in green)
Thanks
strtotime() will return FALSE when it can't parse the date. This is being treated as 0, the epoch time, when you use it as the base time in the second call to strtotime().
Check for that before trying to use the result.
$parsed = strtotime($date);
if ($parsed) {
$date = date('d F y', strtotime('+28 days', $parsed));
} else {
$date = '';
}
You should use DateTime object for storing and manipulating dates.
echo $date !== null ? (new DateTime($date))->add(new DateInterval('P28D'))->format('Your date format here') : '';
https://www.php.net/manual/en/class.datetime.php
Basically it uses a ternary operator to check if $date is null, if it's not, it creates a new DateTime object for the current date, adds 28 days and echoes it in a chosen format. If $date is null, it will just echo an empty string - ''.
Edit: The above is just an one-liner example, a good practice would be getting it into a function.

Comparing two dates in PHP and MYSQL

I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
}else{
}
What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.
Try this :
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
//I want to run some code here
}else{
}
Hope it helps !!!!
One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:
$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
// current hour
}
Timestamps are convenient because:
there is no need to take the format into account;
operations on numbers are usually faster;
the code looks cleaner.
Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49
<?php
$current_datetime = strtotime(date('Y-m-d H:i'));
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
echo 'something';
}else{
echo 'something else';
}
Output:
echo $current_datetime . '<br/>';
2016-10-17 09:19
echo $send_date .'<br/>';
2015-04-13 09:03
// result
something else

Date is inserting as 0000-00-00 00:00:00 in mysql

My $date output is in the foreach loop
09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10,
09/24/09, 02/19/09, 12/21/08
My mysql query(PHP) is as follows
("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");
Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.
I tried with date('Y-m-d H:i:s', $date); but no help.
Note: My database field is datetime type.
Any idea?
You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.
I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:
date('Y-m-d H:i:s', strtotime($date));
The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.
I created my own function for this purpose, may be helpful to you:
function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
if (!is_string($fromDate))
return null ;
try {
$DT = DateTime::createFromFormat($format, trim($fromDate)) ;
} catch (Exception $e) { return null ;}
if ($DT instanceof DateTime){
if (is_array($hms) && count($hms)===3)
$DT->setTime($hms[0],$hms[1],$hms[2]) ;
return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
}
return null ;
}
So in your case, you use format m/d/yy :
$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
//Ok, proceed your date is correct, string is returned.
}
You don't have the century in your date, try to convert it like this:
<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;
Prints:
2011-09-25
Now you can insert $date into MySQL.

timestamp to php from timestamp array

Hi guys i am really new to php and i am trying to convert the timestamp from an xml array but with no sucess , i read everything i found but still can find the way can you please help ?
I am using this code to decode an xml api output
$mysongs = simplexml_load_file('http://example.com/test/xml/');
$timestamp = $mysongs->item->timestamp;
$playtime = date("Y-d-m G-i-s",$timestamp);
If i echo $timestamp it works fine, $playtime doesn't...
Tried with :
echo gmdate("Y-m-d", $timestamp);
&
echo date('Y-m-d H:i:s', $wra);
&
echo '<timeplayed>' . date('Y-m-d G:i:s', $mysongs->item->timestamp) . '</timeplayed>';
Still no luck.. Time is not showing.. If i use this example
echo '<timeplayed>' . date('Y-m-d G:i:s', (1365532902)) . '</timeplayed>';
it works fine.. What am i doing wrong here ?
Update
Finally i found it.. it needed to cast the $timestamp as integer for the date to decode properly as euxneks sugested..
So right code should be
$timestamp = intVal ($mysongs->item->timestamp);
and then
$playtime = date("Y-d-m H-i-s",($timestamp));
& finally echo ($playtime); and it works fine...
Thanks everyone for your replys problem solved
It's likely that you need to cast your result as an integer (it's been a while since I've used simplexml but I'm pretty sure it doesn't automatically type the values received):
http://php.net/intval
Also, strtotime might work too :)
http://php.net/strtotime
You are definitely missing strtotime function, here is an example:
$str = '04/09/2013';
$date = date('Y-m-d H:i:s',strtotime($str));
echo $date;
This will output:
2013-04-09 00:00:00
Updated
Since strtotime is alread used, what about using:
$date = date('Y-m-d H:i:s', ($timestamp));

Converting String to DateTime in PHP

I need to insert the datetime value entered from the HTML form using PHP into the MySQL database. However I receive the Incorrect datetime value error each time I try to execute the code below,
$rosterstartdate=$_GET['rosterstartdate'];
$rosterenddate=$_GET['rosterenddate'];
//$date = date_create_from_format('d/M/Y:H:i:s', $rosterstartdate);
//$date->getTimestamp();
//echo $date;
$date = strtotime($rosterstartdate);
echo date('d/M/Y H:i:s', $date);
// echo DATE_FORMAT($rosterstartdate,"%Y%m%d %H%i%s");
$con=mysql_connect("localhost","root","");
if($con==true){
mysql_select_db("attendance_db",$con);
$query="insert into tblroster values(LAST_INSERT_ID(),'$rosterteam','$rostershifts','$date','$rosterenddate')";
I have tried using each of the different techniques above to do the conversion but it does not work. Any ideas on how this could be inserted
try this:
$date = date('Y-m-d H:i:s', $date);
Instead of echoing it out, use that code to format the date.
However, it looks like what you really want is this:
$rosterstartdate = date('Y-m-d H:i:s', strtotime($rosterstartdate));
$rosterenddate = date('Y-m-d H:i:s', strtotime($rosterenddate));
This way you can just reference those two variables in your query string.
You don't need to format it if you have a unixtime use FROM_UNIXTIME,
change your query as
$rosterstartdate=$_GET['rosterstartdate'];
$rosterenddate=$_GET['rosterenddate'];
//$date = date_create_from_format('d/M/Y:H:i:s', $rosterstartdate);
//$date->getTimestamp();
//echo $date;
$date = strtotime($rosterstartdate);
$con=mysql_connect("localhost","root","");
if($con==true){
mysql_select_db("attendance_db",$con);
$query="insert into tblroster values(LAST_INSERT_ID(),'$rosterteam','$rostershifts',FROM_UNIXTIME($date),'$rosterenddate')";

Categories