I am trying to include a function from one PHP file into another and use the function with a parameter and get a return value. All is good until I run the function, where PHP dies. How can I fix this?
timestamp_reader.php:
<?php
function get_time($timestamp){
$year = substr($timestamp, 0, 4);
$month = substr($timestamp, 4, 2);
if(substr($month, 0, 1) == "0")
$month = substr($month, 1, 1);
$day = substr($timestamp, 6, 2);
if(substr($day, 0, 1) == "0")
$day = substr($day, 1, 1);
$hour = substr($timestamp, 8, 2);
if(substr($hour, 0, 1) == "0")
$hour = substr($hour, 1, 1);
$hour = intval($hour);
if($hour > 12){
$hour = $hour - 12;
$pm = true;
}else $pm = false;
$minute = substr($timestamp, 10, 2);
if(substr($day, 0, 1) == "0")
$day = substr($day, 1, 1);
if($pm) $minute .= " PM";
else $minute .= " AM";
return $month . "/" . $day . "/" . $year . " " . $hour . ":" . $minute;
}
?>
And the file that I want access to this function (note, it is in a different directory):
...some PHP code before this...
include "/project/includes/timestamp_reader.php";
while($row=mysql_fetch_array($result)){
$msg = $row['message'];
$timestamp = $row['timestamp'];
$time = get_time($timestamp);
echo "<p><center>" . $time . " " . $msg . "</center></p>";
}
I'd like to figure this out and use it for a variety of functions so I don't have to type them in every time if possible. Also, I need something similar for creating project-wide variables.
Anyway, thanks for any and all help!
How about you avoid reinventing a wheel ? .. especially so misshapen one :
http://www.php.net/manual/en/function.date.php
http://www.php.net/manual/en/datetime.format.php
Why not use the date() function within PHP?
For example,
$timestamp = "1316922240";
echo date("m-j-Y", $timestamp);
Will print out 09-24-2011 based on that time stamp for right now - if the timestamp was from yesterday, the date echo-ed will be yesterday.
try with require(), it fails if the path is wrong, which I bet is the case.
Related
I have these time value from HTML form using timepicker js.
I want to split the value into three (3) variables which is $hour, $minute and $period.
The problem is I can't split 'AM' or 'PM' value into another variable.
$minute hold the value "00 PM". I want AM or PM store into another variable call $period
What I have done so far as code below.
Time.php
<?php
// $btArray = explode(':', $_POST['app_time']);
$btArray = explode(':', '11:00 PM');
$hour = strlen(trim($btArray[0])) > 1 ? trim($btArray[0]) : '0' . trim($btArray[0]);
$minute = trim($btArray[1]);
$period = trim($btArray[2]);
$query = "UPDATE TABLE
SET
BOOK_TIME = '" . $hour . ":" . $minute . "',
TIME_PERIOD = '" . $period ."'
WHERE
TRACK_NUM = ''
";
?>
My goal is to split the value so I can store it into database.
Appreciate if someone can help me to solve this problem.
Thanks.
$btArray= "7:00 am";
preg_match("/([0-9]{1,2}):([0-9]{1,2}) ([a-zA-Z]+)/", $btArray, $match);
$hour = $match[1];
$min = $match[2];
$period = $match[3];
$query = "UPDATE TABLE
SET
BOOK_TIME = '" . $hour . ":" . $minute . "',
TIME_PERIOD = '" . $period ."'
WHERE
TRACK_NUM = ''
";
Try this,
$time = '11:00 PM';
//first remove right two char
$period = substr($time, -2, 2);
//remove that string from main string
$newTime = str_replace($period, "", $time);
//convert remaining string to array
$btArray = explode(':', $newTime);
//check hour string length and concate 0
$hour = (strlen($btArray[0]) > 1) ? $btArray[0] : '0'.$btArray[0];
$mint = $btArray[1];
echo $hour.'<pre>';
echo $mint.'<pre>';
echo $period.'<pre>';
die;
Output:
11
00
PM
I would rather suggest to use substr() function as the parameters like: hour, minute, seconds are fixed.
First need to check whether the string length of 8.
Then, get parameters depending upon their positions.
If your date format is constant.
<?php
$str = '11:00 PM';
if (strlen($str) == 8) {
$hour = substr($str, 0, 2);
$minute = substr($str, 3, 2);
$period = substr($str, 6, 2);
}
echo '<pre>';print_r('Hour: '. $hour);echo '</pre>';
echo '<pre>';print_r('Minute: '. $minute);echo '</pre>';
echo '<pre>';print_r('AM/PM: '. $period);echo '</pre>';
Output:
Hour: 11
Minute: 00
AM/PM: PM
Working Demo:
You can try below code for your desire output.
$btArray = explode(':', '11:00 PM');
$hour = strlen(trim($btArray[0])) > 1 ? trim($btArray[0]) : '0' . trim($btArray[0]);
$minute_period_array = explode(' ', $btArray[1]);
$minute = trim($minute_period_array[0]);
$period = trim($minute_period_array[1]);
echo 'Hour - ' . $hour . '<br/>';
echo 'Minute - ' . $minute . '<br/>';
echo 'Period - ' . $period . '<br/>';
Output :
Hour - 11
Minute - 00
Period - PM
If you will get the input value always in the same format, you can go this way:
$input = '8:05 PM';
list($hour, $minute, $period) = explode(' ', str_replace(':', ' ', $input), 3);
// And then clean the variables
$hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
$minute = str_pad($minute, 2, '0', STR_PAD_LEFT);
$period = strtoupper(trim($period));
// $hour -> 08, $minute -> 05, $period -> PM
I'm using 2 variables: check-in, check-out
Their format is: dd/mm/yyyy
I want separate the day, month and year into single variables,
in order to compare the integers of:
dd(check-in) with dd(check-out),
mm(check-in) with mm(check-out), and
aaaa(check-in) with aaaa(check-out),
so that the check-in cannot be done after the check-out, and an error appears when somebody try.
On the php file:
$in_date = $_POST['check-in'];
settype( $in_date, "string");
$in_yyyy = substr( $in_date , 6, 4);
settype( $in_yyyy, "integer");
$in_mm = substr( $in_date , 3, 2);
settype( $in_mm, "integer");
$in_dd = substr( $in_date , 0, 2);
settype( $in_dd, "integer");
$out_date = $_POST['check-out'];
settype( $out_date, "string");
$out_yyyy = substr( $out_date , 6, 4);
settype( $out_yyyy, "integer");
$out_mm = substr( $out_date , 3, 2);
settype( $out_mm, "integer");
$out_dd = substr( $out_date , 0, 2);
settype( $out_dd, "integer");
Suppose I typed in input:
check-in: 16/12/2016
check-out: 23/01/2017
However, those are the values the variables takes on:
$in_date = 16/12/2016
$in_yyyy = 2017 // THAT'S WRONG
$in_mm = 01 // THAT'S WRONG
$in_dd =23 // THAT'S WRONG
$out_date = 23/01/2017
$out_yyyy = 2017
$out_mm = 01
$out_dd =23
The problem seems to be caused by "substr". It seems to take on, no matter what, always the last value attributed to it.
Any suggestion?
Assuming you always get the date in the below format, you can use the explode() function in PHP to separate the day, month and year from the date.
$date = '16/12/2016';
$parts = explode('/', '', $date);
$day = $parts[0];
$month = $parts[1];
$year = $parts[2];
unset($parts); // clean up
Your code may look something similar to:
$dates = array(
'check_in' => $_POST['check_in'],
'check_out' => $_POST['check_out']
);
foreach($dates as $_date)
{
settype( $_date, "string");
$parts = explode('/', '', $_date);
$day = $parts[0];
$month = $parts[1];
$year = $parts[2];
settype( $day, "integer");
settype( $month, "integer");
settype( $year, "integer");
}
unset($_date); // clean up
I would strongly recommend that you utilize it with Datetime object when you are working with date/time although explode() or substr() will also work.
$dt = DateTime::createFromFormat('d/m/Y', '16/12/2016');
echo "Year: " . intval($dt->format('Y')) . "\n";
echo "Month: " . intval($dt->format('m')) . "\n";
echo "Day: " . intval($dt->format('d')) . "\n";
Benefit of it is that also you can use this datetime objects to compare your check-in and check-out way easier, or you can even easily calculate nights etc. Try following code:
<?php
$dt = DateTime::createFromFormat('d/m/Y', '16/12/2016');
echo "Year: " . intval($dt->format('Y')) . "\n";
echo "Month: " . intval($dt->format('m')) . "\n";
echo "Day: " . intval($dt->format('d')) . "\n";
$dt_out = DateTime::createFromFormat('d/m/Y', '10/12/2016');
if ($dt > $dt_out) {
echo "Check-in cannot be after check-out\n";
}
$dt_out = DateTime::createFromFormat('d/m/Y', '18/12/2016');
if ($dt < $dt_out) {
echo "This is good!\n";
}
echo "Nights: " . $dt->diff($dt_out)->format("%a") . "\n";
I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');
I am working on a script that will determine when a specific calendar date most recently occurred.
This post, Get the year of a specified month in previous 12 months?, is the basis of my current beta. It was written for a monthly result and not a specific date.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time())
? mktime(0,0,0,$m,$d)
: mktime(0,0,0,$m,$d,date("Y") -1);
$from = date('F jS', $c) . " last occurred in " . date('Y', $c) . ".";
echo $from;
?>
The result of the default value, October 1 is:
"October 1st last occurred in 2012."
For June 11th, as a random example:
"June 11th last occurred in 2013."
All date results are TRUE, except for the result for February 29th:
"March 1st last occurred in 2013."
Obviously, this is a false statement since the desired result is:
"February 29th last occurred in 2012."
I'm kind of stuck, what is the best way to add a true leap year result?
This is calculating last true year. Replace with following codes.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$y = date('Y');
if($m == "February" && $d == "29") $y = $y - ($y % 4);
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time()) ? mktime(0,0,0,$m,$d,$y) : mktime(0,0,0,$m,$d,$y);
$from = date('F jS', $c) . " last occurred in " . $y . ".";
echo $from;
?>
Results
For 2013: Result 2012
For 2012: Result 2012
For 2011: Result 2008
For 2010: Result 2008
$month = 9;
$day = 1;
$timestamp = mktime(0, 0, 0, $month, $day);
if ($timestamp > time()) {
$timestamp = mktime(0, 0, 0, $month, $day, date('Y') - 1);
}
covert timestamp to your desire format.
I've done some reasearch but I did not find any issue. I try to increment a date in a loop in order to test if some files does exist. In fact I would like to make some user play each sevent days. When they played the file is created whith their IP and with the date. So we test in a loop if a file does exist with each date between this days. If it exist we return 1 else we return 0.
I met some trouble I do not really know how to increment a date in php using aloop
I tried something like that
**function afficheTirageAusort() {
//Initialisation des variables
$ip = $_SERVER["REMOTE_ADDR"];
$date_str = date('d-m-y');
$rep = "ip/";
if (!file_exists($rep)) {
fopen($rep, "w+");
}
$fichier = $ip . $date_str . '.txt';
$periode = 7;
$i = 0;
$date_jeu = 0;
//Test de l\'existence du fichier
while ($i <= $periode) {
list($d,$m,$Y)= explode('-',$date_str);
$date2 = Date('d-m-Y', mktime(0, 0, 0, $m, $d + 1, $Y));
$date = Date($date2, mktime(0, 0, 0, $m, $d + 1, $Y));
var_dump($date);
if (file_exists($rep . $ip . $date . '.txt')) {
$var = 0;
} else {
fopen($rep . $ip . $date . '.txt', 'w+');
$var = 1;
//break 1;
}
$i++;
};
return $var;
}
I'm a beginner in php.
anykind of help will be much appreciated.
You will want to use strtotime and continue to use the $date variables:
// Setup the dates
list($d, $m, $Y) = explode('-', $date_str);
$date2 = Date('d-m-Y', mktime(0, 0, 0, $m, $d, $Y));
$date = Date($date2, mktime(0, 0, 0, $m, $d, $Y));
//Test de l\'existence du fichier
while ($i <= $periode) {
$date = strtotime("+1 day", strtotime($date)); // 1 day past previous date
$date2 = strtotime("+1 day", strtotime($date)); // 1 Day past the $date var
echo date("Y-m-d", $date);
var_dump($date);
if (file_exists($rep . $ip . $date . '.txt')) {
$var = 0;
} else {
fopen($rep . $ip . $date . '.txt', 'w+');
$var = 1;
//break 1;
}
$i++;
};
return $var;
try something along these lines.
$todaysdate = date("Y-m-d H:i:s");
$tomorrowsdate = date("Y-m-d H:i:s", date()+86400);
essentially i just added 86400 seconds to the current date, and there are 86400 seconds in a day, so I just added 1 day.
Wouldn't it be easier for you to create date out of UNIX Timestamp and increment it? Like this:
$time = time() + (3600 * 24);
$date = date('d-m-Y', $time);