I am trying to do looping but I can't - php

I am trying to make for loops using date function but I can't. In my case, I am trying to loop 2001-feb to 2009-jan and want to insert date but I can't. Can anyone help me? Here is my code:
for($start_year; $start_year<= $end_year; $start_year++)
{
for($start_month; $start_month<= $end_month; $start_month++)
{
$date_input = $start_year."-".$start_month."-27";
}
}

Looks like PHP.
for($start_year; $start_year<= $end_year; $start_year++)
You've not specified a starting value for $start_year, so unless you've defined that variable elsewhere, this is a syntax error. As well, since you're starting/ending on different months, you can't really use a loop for that without jumping through hoops. You'd probably be better off with something like this:
$date = strtotime("2001-02-01 00:00:00");
$end = strtotime("2009-01-01 00:00:00");
do {
echo date('Y-m', $date), "-27";
$date = strtotime("+1 month", $date);
} while ($date <= $end);
Note that strtotime is only one way of doing this. You could use the DateTime object with a 1-month DateInterval, but that's for PHP 5.3+ only.

Related

delete hours, minutes and secconds in age Unix PHP?

I work on one project with PHP and Mysql and I need to calculate the ages but I need delete the hours, minutes and seconds part. Here is an example:
The date of birth 2018-03-06 17:35:00 but
I need 2018-03-06 00:00:00
Here is my code:
function FetchAgeCaduce($MaxDias=3){
$fechaInicial = time();//date("Y-m-d");
$fecha = date("d/m/Y",$FechaFinal);
$fechaInicial = strtotime("d/m/Y",$fecha);
for ($i=0; $i<$MaxDias; $i++)
{
$Segundos = $Segundos + 86400;
$caduca = time()+$Segundos;//date("D",time()+$Segundos);
$var = date("D",$caduca);
if ($var == "Sat")
{
$i--;
}
else if ($var == "Sun")
{
$i--;
}
else
{
$FechaFinal = time()+$Segundos;
}
}
return $FechaFinal;
}
How can I work on it to get the expected result?
The right way / The MySQL way:
Store your data as DATE in MySQL, not DATETIME. DATE itself is described here. It does not store time, so you'll always have 00:00:00 as default.
The less right way / The PHP way:
Jay, Zeus, Freaking, K. Reist. Learn to use DateTime already, stop using date! It's like every second question here and noone learns DateTime!
Use it!
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
The output:
2018-03-06 00:00:00
P.S. $FechaFinal on line 5 is not defined.
You can format the date on either the application or database layer.
Using MySQL
You can use MySQL DATE_FORMAT Function
to parse the date into the wanted format.
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') dob;
See DEMO on SQL Fiddle.
Using PHP
Say you don't want to format the date in the database layer, may be because you would need to use the time part in some other calculations. Use the date functions as illustrated below:
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
//getting the expected date from the formatted string
$formateDate = DateTime::createFromFormat('Y-m-d H:i:s', $dt->format("Y-m-d 00:00:00"));

PHP, Date: A Dot appended to a month short representation

I have
date("M.", $datetime)
I want to get this output:
Jan.
Feb.
Mar.
Apr.
May (no dot necessary)
Jun.
Jul.
…
I dont like the idea of an if-statement to check the length/number of month every time a date is generated.
Is there a approach that is more simple? Like changing the month-name in general? Or hooking into the date function itself to implement an if-statement that runs every time the date function runs.
Thanks
If you don't want the dot to appear after May month, you will need a check of some sort - which normally is an if. You could do something like this, check if the month returned by date() isn't May, and add a dot after if it isn't.
$date = date("M", $datetime);
if (date("M") != "May")
$date .= ".";
Otherwise you'd need to implement a function of your own, but in the end - you will have to end up with this again, there's really no way around it - and this is by far the simplest and cleanest way.
You could wrap this into a function. You can't alter the date() function directly, but you can create one of your own.
function my_date($format, int $timestamp = null) {
if ($timestamp === null)
$timestamp = time();
$date = date($format, $timestamp);
if ($format == "M" && date("M", $timestamp) != "May")
$date .= ".";
return $date;
}
Then use it as
echo my_date("M", $datetime);
This seems to be a bit of a hammer to crack a nut, or to avoid an IF statement in this case, but you can create an array with your month names in it and use that to output different month names if you like
$m_arr = [0,'Jan.','Feb.','Mar.','Apr.','May','Jun.',
'Jul.', 'Aug.', 'Sep.','Oct.','Nov.','Dec.'];
$m = (int)date('n', $datetime);
echo $m_arr[$m];

Why is my while loop not working when no echo is put inside?

I got a pretty simple code that will take 2 dates and loop my data until the end date is reached.
$start = new DateTime($senddate);
$now = new DateTime("NOW");
$end = new DateTime ($end);
//We check if starting date is >= now()
if ($start->date <= $now->date){
$start = $now;
}
$i=0;
if ($frequency==4){
while ($start->date <= $end->date) {
$calcdate[$i]=$start->date;
$start->modify('+1 month');
$i++;
echo '<!--';
print_r($start);
echo '-->';
}
As you see there is a print_r inside the loop.
Everything work fine :)
BUT, if I remove it, then the loop never end .. I tried to add if($i>50) exit; without anymore success. I don't understand why this loop doesn't work when no pint_r is inside.
Thanks for your help
I would suggest that you have a read of the PHP DateTime manual, there is a lot of good information there that will help you with what you are trying to do.
As far as I can tell, you are trying to carry out an operation on a monthly basis between two dates that span the current date. There is a simpler way of doing it utilising the DatePeriod class.
Something like this:-
$start = new \DateTime('yesterday');// Just for demo purposes
$now = new \DateTime(); //No need for "now" as it is the default
$end = new \DateTime('+ 6 month');// again, for demo purposes
$interval = new \DateInterval('P1M');
if($now >= $start){ // you can do direct comparisons on DateTime objects
$period = new \DatePeriod($start, $interval, $end);
foreach($period as $date){
// Each $date is a DateTime instance that you can
// operate on as you see fit, I have just var_dumped it out.
var_dump($date);
}
}
The above code can be seen working here http://3v4l.org/1I30E
My error came from this line $calcdate[$i]=$start->date;
It seems that this gives somme unexpected behavior (in this case), I tried using $calcdate[]=$start->format('Y-m-d H:i:s'); which gave the expected results ... Don't know why my script didn't worked with the date method. If anyone knows ..

check if datetime from sql is today

I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

Categories