Michael Jones
Michael Jones

Reputation: 2282

Take Current MYSQL Timestamp And Subtract It From 24 Hours

One thing that has always confused me is Time in coding. I am very confused on how to go about doing this! Simply, I have a MySql Timestamp, and I want to subtract that from 24 hours.

Basically, I am trying to code something that only lets you complete an action once every 24 hours, and then if they try to complete it more then once it will tell them how long they have to wait to do it again.

This is the code I currently have:

$dailylogincheck = 2015-08-16 13:30:32 //MySQL Timestamp
date_default_timezone_set("America/New_York");
$lastloginbonus = new DateTime($dailylogincheck);
$currenttime = $lastloginbonus->diff(new DateTime(date("Y-m-d H:i:s")));

I don't have to use this code (if there is a better way to do this). So I would just like to subtract the current Timestamp from 24 hours, but I have no clue how to do this in PHP :( Please Help!

P.S. I would simply like to display a sentence like the following: You have already done this within the past 24 hours. Please come back in X hours X minutes and try again.

Upvotes: 3

Views: 491

Answers (2)

user557846
user557846

Reputation:

hope this works :-)

   <?php


$dailylogincheck = '2015-08-16 13:30:32';

$end = new DateTime($dailylogincheck);
$end->add(new DateInterval('P1D'));//add 1 day to find end date
$now = new DateTime('now');

$interval = $end->diff($now);

if($end->diff($now)->days >= 1){
 echo 'go for it'; 
}else{
echo $interval->format('%H hours, %i minutes until you can XXX');

}

Upvotes: 4

JD Williams
JD Williams

Reputation: 75

As Dagon said, doing it in mysql is the best approach... but to address your php question, DateTime will accept a number of simple modifiers:

<?php

$lastBonus = new DateTime("-1 day"); // Last bonus was exactly 24 hours ago
$canNotGetNewBonus = new DateTime("-1 hour"); // Attempting another bonus 23 hours later
$canGetNewBonus = new DateTime("+1 hour"); // Attempting another bonus 25 hours later

var_dump($lastBonus->diff($canNotGetNewBonus)->days >= 1);
var_dump($lastBonus->diff($canGetNewBonus)->days >= 1);

Upvotes: 2

Related Questions