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";
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 PHP Version 5.5.15 and running php (on my local windows machine) with Xampp.
I have troubles with the variable $time. $date and $date2 are working.
here's the code:
<?php
//include_once('connect.php')
function currencyquote() {
$from = 'EUR';
$to = 'USD';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='.$from .$to .'=X';
$handle = #fopen($url,'r');
if($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$date = $allData[2]; //ex.: "2/18/2015"
$time = $allData[3]; //ex.: "1:48pm" -> New York local time
$close = $allData[1]; // ex.: 1.3151
echo 'the $result = ' . $result .'<br />';
echo 'the $time = ' .$time. '<br />';
$date2 = date_create_from_format("h:ia","01:50pm");
echo 'the $date2 = ' . date_format($date2, "H:i:s") . "<br />";
$date3 = "01:50pm";
$date=date_create_from_format("h:ia",$date3);
echo 'the $date = ' . date_format($date,"H:i:s") . "<br />";
// this is what i want to use :
$time1 = date_create_from_format("h:ia", $time);
echo 'the $time1 = ' . date_format($time1,"H:i:s") . "<br /><br />"; // this line is line 30 of the code
//with strtotime:
echo 'using \'date\' = ' . date("h:i:s", strtotime($allData[3])) . "<br />";
echo 'using \'date()\': '.date('H:i:s', strtotime($time));
}
currencyquote();
?>
and here are the results of the php-jury:
the $result = "EURUSD=X",1.1372,"2/19/2015","7:20am"
the $time = "7:20am"
the $date2 = 13:50:00
the $date = 13:50:00
Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in C:\xampp\htdocs\Nofrafin\php\downloader.php on line 30
the $time1 =
using 'date' = 01:00:00
using 'date()': 01:00:00
The message you get most likely means that $time1 is set to false. And the reason from that should be that date_create_from_format() can't match the date format h:is with the variable you supply, $time.
Moving further up, you have
$time = $allData[3]; //ex.: "1:48pm"
I tried changing to $time = '1:48pm'; and that worked perfectly. So that means you don't get the data you think from the csv.
I tried to download the same file as you do and got this back:
"EURUSD=X",1.1371,"2/19/2015","7:50am"
And that's the reason it doesn't work - $time is set to "7:50am" with a trailing newline, not 7:50am. Remove the double quotes (e.g. $time = trim(str_replace('"', '', $time)); and you should hopefully be fine. :)
Firstly:
For CSV reading use fgetcsv() function, so you will not have to filter quotes from CSV output and there is no need to do explode().
if($handle) {
$result = fgetcsv($handle, 4096);
fclose($handle);
}
$date = $result[2]; //ex.: "2/18/2015"
$time = $result[3]; //ex.: "1:48pm" -> New York local time
$close = $result[1]; // ex.: 1.3151
...
$time1 = date_create_from_format("G:ia", $time);
Secondly:
You should carefully filter the input string for date_create_from_format function.
such as:
$time = trim(str_replace("\"","", $time)); // you will get something like 7:20am
and then:
$time1 = date_create_from_format("G:ia", $time); // G - for 24-hour format without leading zeroes in your case
but use the first solution (fgetcsv()) anyway
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);
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.
My attempted solution was:
$date = "Nov 30 2009 03:00:00:000PM";
echo date("F Y", strtotime($date));
Expected result should be: "November 2009"
Any other simple solutions?
While a regex could do it, here's something you might understand easier
$date_bad = "Nov 30 2009 03:00:00:000PM";
$piece_date = array();
$piece_date = explode(' ', $date_bad);
$date_good = $piece_date[0] .' '. $piece_date[1] .', '. $piece_date[2] .' ';
$piece_time = array();
$piece_time = explode(':', $piece_date[3]);
// check if the last part contains PM
if ( is_numeric(strpos($piece_time[3], 'PM')) )
{
$ampm = 'PM';
}
// check if the last part contains AM
elseif ( is_numeric(strpos($piece_time[3], 'AM')) )
{
$ampm = 'AM';
}
// no AM or PM is there, so it's a 24hr string
else
{
$ampm = '';
}
$date_good .= $piece_time[0] .':'. $piece_time[1] .':'. $piece_time[2] . $ampm;
echo date("F", strtotime($date_good));
date_default_timezone_set ('Etc/GMT-6');
$unixtime = strtotime($date_bad);
$date = date("F Y",$unixtime);
echo $date;
Time Zones