changing my SQL Timestamp into a d-m-Y in php - php

In my database I use CURRENT_TIMESTAMP to keep track of the registration dates for my new users.
Now I wish to generate a list of users who signed up in the past 7 or 30 days.
I figured it would be as simple as explained in this topic;
Get 30 days back date along with time
But my current code generates an unexpected output.
for($i = 0; $i < $userlenght; $i++){
$comparedate = strtotime(date('Y-m-d', $user[$i]["date"]));
echo $comparedate . "<br/>";
if($user[$i]["date"] > $last){
//do stuff here with the users who match.
}
}
This displays the $comparedate value as "-3600" and I have no idea why.
Can anyone provide some insight?

SQL Timestamp is returned formatted as a string, so you need to instruct PHP to read the string as a date formatted value. To do so you need to use strtotime().
Try the following:
for($i = 0; $i < $userlenght; $i++){
$comparedate = strtotime(date('Y-m-d', strtotime($user[$i]["date"])));
echo $comparedate . "<br/>";
if($user[$i]["date"] > $last){
//do stuff here with the users who match.
}
}

Your problem is that $user[$i]['date'] is a MySQL Timestamp which looks like 2018-09-14 11:09:10, and is not a valid input to date. You can just remove the call to date and your code should work fine:
$comparedate = strtotime($user[$i]["date"]);

Related

Retrieve previous days data (PHP script), and send data using Amazon SNS

I have a piece of code that will display the results and comparisons of a number(3) of database queries in a browser. It displays the differences in the figures of each DB. It works and that is all okay. Now, what I have to do is forget about the webpage and have the php script run once a day, say at 3am, and the script has to look for any difference in the DB figures for the previous day. If any differences are discovered, using Amazon Simple Notifications Service, an email will be sent to all the subscribers with the details those differences. Here is the part of my code that is new from the previous working script (the one for the browser):
if ($total_results) {
foreach ($total_results as $cid => $dates) {
foreach($dates as $row) {
$dbOne_total = $row['dbOne_total'];
$dbTwo_total = $row['dbTwo_total'];
$dbThree_total = $row['dbThree_total'];
$difference = ($dbTwo_total - $dbOne_total);
$difference_bill = ($dbThree_total - $dbOne_total);
$mismatchFile = fopen("mismatch.txt", "w");
$issue = "";
while($startDate == date('Y-m-d', strtotime('-1 day'))) {
if (($difference_bill > 0) || ($difference > 0)) {
$issue = ($row["company"] ." ". $row["company_id"]. " ". "dbTwo Difference". " ". $difference. " "."dbThree Difference". " ". $difference_bill);
print_r($issue);
topic("DATABASE-MISMATCH")->send("List of mismatches between databases", "Issue: $issue/n"); // for ASN
}
}
fwrite($mismatchFile, $issue);
fclose($mismatchFile);
}
}
$startDate is a variable I am using throughout the code as I have sql queries running that need this date to get the info.
I'm questioning this line:
while($startDate == date('Y-m-d', strtotime('-1 day'))) {
I'm not sure if strtotime is the best option (I'm worried about possible format issues). Is there a better way to get the data from the previous day?
I'm wondering if I am approaching this problem in the correct way? I would also appreciate any advice on how to the $issue variable into the Amazon SNS email body, as a list, or would it be better to create a file and send that as an attachment?
I am still quite a newbie to PHP and so any assistance, or a helpful point in the right direction, would be so much appreciated.
while($startDate == date('Y-m-d', strtotime('-1 day'))) is a wrong approach. It always returns true and the cycle is infinite.
If you want just a one time day before, use
$date = new \DateTime('now - 1 day');
echo $date->format('Y-m-d');
If you need to do it in a loop
$date = new \DateTime(); // now here
for($i = 1; $i <= 10; $i++) {
$date->sub(new \DateInterval('P' . $i . 'D'); // $i days before, $i>0
}

php for loop for date increment each time

I want to loop a date so that every time date is increment by previous date. my code is here. plz reply anyone, thanks in advance
$today = date('Y-m-d');
for($i=1; $i<=4; $i++){
$repeat = strtotime("+2 day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
I want result as if today is 2016-04-04 than, 2016-04-06, 2016-04-08, 2016-04-10, 2016-04-12.
actually i want to make a reminder date where user enter reminder. lets a user want to add reminder today and want repeat it 5 time after 2days, 3days or what ever he wants, in next comming day. than how i repeat date with for loop.
Try this:
<?php
$today = date('Y-m-d');
for($i=1; $i<=4; $i++)
{
$repeat = strtotime("+2 day",strtotime($today));
$today = date('Y-m-d',$repeat);
echo $today;
}
Output:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
The easiest way is what answer
aslawin
The below example is to go through the date
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$step = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $step, $end);
foreach ($period as $dt)
{
<sample code here>
}
You can try this:
$today = date('Y-m-d');
for($i=1; $i<=8; $i++){
if($i%2 == 0){
$repeat = strtotime("+$i day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
In this example, you can use $i%2 == 0 with limit <= 8
Use a for loop with base 2, then directly output your dates:
for( $i=2; $i<9; $i=$i+2 )
{
echo date('Y-m-d', strtotime( "+ $i days" )) . PHP_EOL;
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
actually i want to make a reminder date where user enter reminder.
lets a user want to add reminder today and want repeat it 5 time after
2days, 3days or what ever he wants, in next comming day. than how i
repeat date with for loop.
I'll help with the above. First of all I will just say I have a huge personal preference towards the DateTime object over simply using date it's more flexible and a hell of a lot more readable in my opinion, so when working with dates I would always suggest using that over date()
So here is some Code:
$date = new DateTime(); // Pretend this is what the User entered. We got it via $_POST or something.
$interval = 2; // Repeat x times at y day intervals. (Not including the initial)
$repeatAmount = 2; // Repeat the reminder x times
for ($i = 0; $i <= $repeatAmount; ++$i) {
echo $date->format('d/m/Y');
$date->modify('+'. $interval .' day');
}
$date = new DateTime()Imagine this is the date the user entered, this is our starting point, our first reminder will at this time.
$interval and $repeatAmount are the interval in days, i.e. I want this to every 2 days and the amount of times you want it to repeat, in our example 2.
for ($i = 0; $i <= $repeatAmount; ++$i) { We want to loop as many times as the user says they want to repeat. Little note ++$i tends to be a very minor performance boost over $i++ in some scenarios, so it is usually better to default to that unless you specifically need to use $i++
echo $date->format('d/m/Y'); Simply print out the date, i'll let you handle the reminder logic.
$date->modify('+' . $interval . ' day'); Increment the dateTime object by the interval that the user has asked for, in our case increment by 2 days.
Any questions let me know.

PHP DateInterval and modify does not advance time

I have a series of seconds between events.
I want to calculate the time of the current event.
So I get the time when the process starts and add the seconds.
But this does not advance the minutes for some reason.
I have the following code:
$time = '2016-03-10 10:03:07';
$date_obj = new DateTime($time);
for ($i = 0; $i < 10; $i ++) {
$date_obj->add(new DateInterval("PT20S"));
// I also tried $date_obj->modify('+ 20 second");
// but the result is the same.
$time = $date_obj->format("H:m:s");
echo $time . "<br>";
}
Which outputs:
10:03:27
10:03:47
10:03:07
10:03:27
etc
How can I add seconds so that it advances the minutes instead?
Tried this on my server and this PHP Fiddle, same result:
https://3v4l.org/oSCsk
You are echo'ing the month instead of the minute in this line:
$date_obj->format("H:m:s");
Try changing it to:
$date_obj->format("H:i:s");
More info about the accepted date format:
http://php.net/manual/en/function.date.php

PHP Incrementing date with day name

I am currently attempting to get a list of dates from a current date using the following format so that I can process it and stick it in my database
Saturday/02-05-2015
So far, i've managed to get the system to output the date correctly, but can not get it to increment in single day values.
My current code to attempt to increment this is the following
$tempStartDateN = ("$splode[0]/$splode[1]/$splode[2]/$splode[3]");
echo $tempStartDateN;
$tempStartDateN = date('l/d/m/Y', strtotime($tempStartDateN . ' + 1 day'));
echo $tempStartDateN;
I am currently using explode to process the data after the increment, which works fine, but can not get the date itself to increment as long as the day name is included.
Currently, the time is got using this code, which is processed afterwords using explode
$OldDateArray = date("Y/m/d/l");
So to keep a long question short, what is the best way to increment a date that requires the day name, day, month then year?
EDIT:
Heres my current code, managed to get this far thanks to SamV
$date = date("l/d/m/Y");
echo $date;
echo ('</br>');
list($weekdayName, $dateString) = explode("/", $date, 2);
$dateObj = new \DateTime($dateString);
for($i=0; $i<=5; $i++){
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
echo ('</br>');
}
What this does however is:
Friday/01/05/2015
Tuesday/06/01/2015
Wednesday/07/01/2015
Thursday/08/01/2015
Friday/09/01/2015
Saturday/10/01/2015
Sunday/11/01/2015
this means that date and month are swapping around, what is causing this?
You don't need to parse the week day name to add days onto a date.
$date = "Saturday/02-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "02-05-2015"
$dateObj = new \DateTime($dateString);
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
I used the DateTime class, here is the documentation.
I wrote out what you are trying to do yourself, not sure what is causing your issue. This code works though.
$date = "Friday/01-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "01-05-2015"
$dateObj = new \DateTime($dateString);
for($i = 0; $i < 5; $i++) {
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y") . '<br>';
}
Outputs:
Saturday/02/05/2015
Sunday/03/05/2015
Monday/04/05/2015
Tuesday/05/05/2015
Wednesday/06/05/2015
If strtotime is able to parse a date it returns the timestamp. Why not add to it the number of seconds in a day? Smth. like $timestamp += 24 * 3600;
P.S. As far as I can understand, strtotime may accept timestamp as second argument (http://us2.php.net/manual/en/function.strtotime.php) smth. like $timestamp = strtotime('+1 day', $timestamp);

How do I calculate the visitors for the last 24 hours?

I have the following code:
$ips = file_get_contents($_SERVER['DOCUMENT_ROOT']."/visitors.txt");
$arr = explode(",",$ips);
$today = strtotime(date('Y-m-d H:i:s'));
for ($n = 0, $max = count($arr); $n <= $max; $n++) {
$visArr = explode("#",$arr[$n]);
$visDate = strtotime($visArr[1]); //$visArr[1] = 2011-12-27 14:10:45
if($visDate < $today){
unset ($arr[$n]); //remove array item if its date not within 24 hours
}
}
The data is stored like this:
xxx.xxx.xxx.xxx#2011-12-27 11:56:24,
xxx.xxx.xxx.xxx#2011-12-28 11:56:24,
I want to get the visitors from the last 24 hours.
I don't want to use MySQL db, I just want to use the txt file but I'm stuck.
Thanks in advance.
I can see 2 problems:
1st you are comparing the stored time with current time and saying that it will filter array item if its date not within 24 hours..
I think you should use $today = strtotime("-1 day");
and name yesterday instead of today..
Secondly and reason of error is that you are exploding data in file with , which will give you "" ie null for last element in array..and thats why strtotime function is giving error for that value..
what you should do is:
if($visArr[1])
{
$visDate = strtotime($visArr[1]); //$visArr[1] = 2011-12-27 14:10:45
if($visDate < $today){
unset ($arr[$n]); //remove array item if its date not within 24 hours
}
}

Categories