PHP Day count function writing - php

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');

Related

Convert timestamp with dots in PHP ("yyyy.mm.dd hh:nn:ss.zzz")

I'm trying to convert strings with hungarian datetime format, but no success because of the dot-separators:
<?php
$dtime = DateTime::createFromFormat("YY'.'MM'.'DD HH:MM:II frac", "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Isn't it possible without "string-replace" like this:
strtotime(preg_replace("/([0-9]{4})\.([0-9]{2})\.([0-9]{2})/",'${1}-${2}-${3}',$xml->delivery_time)) ?
(I'm new to PHP 5 and I'm shocked it can not simply convert a common date format. Searched 200+ results, wasted 4+ hours ... no success.)
The correct format is stored in the $format variable:
(Note: the v (millisec) modifier has only been added since v7.3)
<?php
$format = 'Y.m.d H:i:s.v';
$dtime = DateTime::createFromFormat($format, "2020.07.22 22:41:36.258");
$timestamp = $dtime->getTimestamp();
echo("Result: " . $timestamp . "<br>");
?>
Result: 1595457696
This solution will also work for PHP versions below 7.3
// convert a hungarian datetime to a timestamp
function toTimestamp($dt)
{
$format = 'Y.m.d H:i:s.';
if (version_compare(PHP_VERSION, '7.3.0', '<')) {
$dt = explode('.', $dt);
$dt[3] = intval($dt[3] * 1000);
$dt = implode('.', $dt);
$format .= 'u';
} else {
$format .= 'v';
}
return DateTime::createFromFormat($format, $dt)->getTimestamp();
}
$timestamp = toTimestamp('2020.07.22 22:41:36.258');
var_dump($timestamp);

PHP Datetime Convert slash to minus

I want to convert my datetime 08/11/2013 to 2013-08-11.
I was trying this, but it did not work as it suppose to.
$date = $_POST['gt_date']; // Getting 08/11/2013
$date = explode("/", $date); // Exploding the / character into array
$datetime = $date[2] + '-' + $date[0] + '-' + $date[1];
Any Ideas?
You can pass it to DateTime to format it for you.
$date = new DateTime('08/11/2013');
echo $date->format('Y-m-d');
I don't know what the + does, but changing your code to the following will work:
$datetime = $date[2].'-'.$date[0].'-'.$date[1];
Edit: I guess the + was adding them together. Was the result you were getting 2032?
Here's a function that will return your format so that you don't have to repeat your code.
function makeDateFormat($date) {
$date = $_POST['gt_date'];
$date = explode("/",$date);
$new_date = array($date[2], $date[0], $date[1]);
$date = implode("-",$new_date);
return $date;
}
This issue is caused by the "+" operator, replace it with "." operator. You could use this function:
function formatDate($date) {
$arr = explode("-",$date);
$year = $arr[2];
$month = $arr[1];
$day = $arr[0];
return $year."-".$month."-".$day;
}
Nice function but correction is this below if you want to covert format as well:
echo makeDateFormat('13/02/23','Y-m-d');
function makeDateFormat($date,$date_format) {
$date = explode("/",$date);
$new_date = array($date[2], $date[1], $date[0]);
$date = implode("-",$new_date);
$date=date($date_format,strtotime($date));
return $date;
}
Another way if your require to format date as per your requirement:
$date=explode("/","13/02/23");
$new_date_format=date('Y-m-d',strtotime($date[2].'-'.$date[1].'-'.$date[0]));

incrementing a date in a loop

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);

PHP add 1 month to date

I've a function that returns url of 1 month before.
I'd like to display current selected month, but I cannot use simple current month, cause when user clicks link to 1 month back selected month will change and will not be current.
So, function returns August 2012
How do I make little php script that adds 1 month to that?
so far I've:
<?php echo strip_tags(tribe_get_previous_month_text()); ?>
simple method:
$next_month = strtotime('august 2012 next month');
better method:
$d = new Date('August 2012');
$next_month = $d->add(new DateInterval('P1M'));
relevant docs: strtotime date dateinterval
there are 3 options/answers
$givendate is the given date (ex. 2016-01-20)
option 1:
$date1 = date('Y-m-d', strtotime($givendate. ' + 1 month'));
option 2:
$date2 = date('Y-m-d', strtotime($givendate. ' + 30 days'));
option 3:
$number = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($givendate)), date('Y', strtotime($givendate)));
$date3 = date('Y-m-d', strtotime($date2. ' + '.$number.' days'));
You can with the DateTime class and the DateTime::add() method:
Documentation
You can simple use the strtotime function on whatever input you have to arrive at April 2012 then apply the date and strtotime with an increment period of '+1 month'.
$x = strtotime($t);
$n = date("M Y",strtotime("+1 month",$x));
echo $n;
Here are the relevant sections from the PHP Handbook:
http://www.php.net/manual/en/function.date.php
https://secure.php.net/manual/en/function.strtotime.php
This solution solves the additional issue of incrementing any amount of time to a time value.
Hi In Addition to their answer. I think if you just want to get the next month based on the current date here's my solution.
$today = date("Y-m-01");
$sNextMonth = (int)date("m",strtotime($today." +1 months") );
Notice That i constantly define the day to 01 so that we're safe on getting the next month. if that is date("Y-m-d"); and the current day is 31 it will fail.
Hope this helps.
Date difference
$date1 = '2017-01-20';
$date2 = '2019-01-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
Since we know that strtotime(+1 month) always adds 30 days it can be some troubles with dates ending with the day 31, 30 or 29 AND if you still want to stay within the last day of the next month.
So I wrote this over complicated script to solve that issue as well as adapting so that you can increase all type of formats like years, months, days, hours, minutes and seconds.
function seetime($datetime, $p = '+', $i, $m = 'M', $f = 'Y-m-d H:i:s')
{
/*
$datetime needs to be in format of YYYY-MM-DD HH:II:SS but hours, minutes and seconds are not required
$p can only be "+" to increse or "-" to decrese
$i is the amount you want to change
$m is the type you want to change
Allowed types:
Y = Year
M = Months
D = Days
W = Weeks
H = Hours
I = Minutes
S = Seconds
$f is the datetime format you want the result to be returned in
*/
$validator_y = substr($datetime,0,4);
$validator_m = substr($datetime,5,2);
$validator_d = substr($datetime,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
$datetime = date('Y-m-d H:i:s', strtotime($datetime));
#$p = either "+" to add or "-" to subtract
if($p == '+' || $p == '-')
{
if(is_int($i))
{
if($m == 'Y')
{
$year = date('Y', strtotime($datetime));
$rest = date('m-d H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $year + $i;
}
else
{
$ret = $year - $i;
}
$str = $ret.'-'.$rest;
return(date($f, strtotime($str)));
}
elseif($m == 'M')
{
$year = date('Y', strtotime($datetime));
$month = date('n', strtotime($datetime));
$rest = date('d H:i:s', strtotime($datetime));
$his = date('H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $month + $i;
$ret = sprintf("%02d",$ret);
}
else
{
$ret = $month - $i;
$ret = sprintf("%02d",$ret);
}
if($ret < 1)
{
$ret = $ret - $ret - $ret;
$years_back = floor(($ret + 12) / 12);
$monts_back = $ret % 12;
$year = $year - $years_back;
$month = 12 - $monts_back;
$month = sprintf("%02d",$month);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
if($ret > 12)
{
$years_forw = floor($ret / 12);
$monts_forw = $ret % 12;
$year = $year + $years_forw;
$month = sprintf("%02d",$monts_forw);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
else
{
$ym = $year.'-'.$month;
$new_date = $year.'-'.$ret.'-'.$rest;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$ym = $validator_y . '-'.$validator_m;
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
}
elseif($m == 'D')
{
return (date($f, strtotime($datetime.' '.$p.$i.' days')));
}
elseif($m == 'W')
{
return (date($f, strtotime($datetime.' '.$p.$i.' weeks')));
}
elseif($m == 'H')
{
return (date($f, strtotime($datetime.' '.$p.$i.' hours')));
}
elseif($m == 'I')
{
return (date($f, strtotime($datetime.' '.$p.$i.' minutes')));
}
elseif($m == 'S')
{
return (date($f, strtotime($datetime.' '.$p.$i.' seconds')));
}
else
{
return 'Fourth parameter can only be any of following: Valid Time Parameters Are: Y M D Q H I S';
}
}
else
{
return 'Third parameter can only be a number (whole number)';
}
}
else
{
return 'Second parameter can only be + to add or - to subtract';
}
}
else
{
return 'Date is not a valid date';
}
}

Calculate years from date

I'm looking for a function that calculates years from a date in format: 0000-00-00.
Found this function, but it wont work.
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
outputs nothing :/
i have error reporting on but i dont get any errors
Your code doesn't work because the function is not returning anything to print.
As far as algorithms go, how about this:
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
This is the same algorithm (just in PHP) as the accepted answer in this question.
A shorter way of doing it:
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
An alternative way to do this is with PHP's DateTime class which is new as of PHP 5.2:
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
See it in action
A single line function can work here
function calculateAge($dob) {
return floor((time() - strtotime($dob)) / 31556926);
}
To calculate Age
$age = calculateAge('1990-07-10');
You need to return $yearDiff, I think.

Categories