how can I make a conditional statement like if date("Y-m-d h:i:s"); is more than 30 seconds after date("Y-m-d h:i:s");.
I've previously used something like date("Y-m-d h:i:s"); < date("Y-m-d h:i:s"); + 30, however this doesn't seem to work.
Help?
Use strtotime() to convert them to UNIX time.
E.g.:
if(strtotime($date2) - strtotime($date1) > 30) {
// $date2 is more than 30 seconds after $date1
}
or
if(abs(strtotime($date2) - strtotime($date1)) > 30) {
// $dates are more than 30 second apart
}
Use strtotime() to convert both dates to a unix timestamp, then add the wanted amount of seconds to the second and do an integer comparison.
Use unixtime, instead. Just convert your date("Y-m-d h:i:s"); to date("U") or just time().
strototime() could help you with this.
It shows the time in seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). Then this method $unixtime + 30 will work fine as well ;)
It looks like you are trying to compare database date fields (like mysql DATETIME). Use the database systems date and time functions to compare date values (like DATE_ADD() or + and with simple < or > in MySQL).
Related
I am writing a login system in PHP and would like a to implement a function that checks if the 15 minutes has elapsed since the last failed login attempt.
In the MySQL database in my users table there is a column called last_login_datetime which is defined as SQL's DATETIME format, ex. 2018-02-24 21:12:57.
This is the code I am using to check if 15 minutes has elapsed since the last login fail
$dateTime = date("Y-m-d H:i:s");
if($row['user_locked']==$statusY AND $dateTime - strtotime($row['last_loginfail_datetime'] > 15 * 60))
{
.....
}
This does not seem to work for me at the moment and was hoping if someone could point out where I am going wrong?
Thanks in advance.
It doesn't work because you are substracting unix time from a string date. What you need to do is to get $dateTime as unix time.
$dateTime = strtotime("now");
Just use strtotime($dateTime) instead of $dateTime in the if condition. strtotime returns a UNIX tiemstamp i.e: the number of seconds since January 1 1970 00:00:00 GMT
$dateTime = date("Y-m-d H:i:s");
if($row['user_locked']==$statusY AND strtotime($dateTime) - strtotime($row['last_loginfail_datetime'] > 15 * 60))
{
.....
}
Your code won't work because your date will be read as a string. Try this instead:
$dateTime = strtotime("now");
if($row['user_locked']==$statusY AND $dateTime - strtotime($row['last_loginfail_datetime'] > 15 * 60))
{
.....
}
I have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);
I tried to save time in format YYYY-mm-dd 23:59:59 to mysql database column with datetime. I don't understand why minutes and seconds are ignored always 00 ? Thank you very much for help.
PHP:
$time = strftime('%Y-%m-%d %H:%i:%s', time());
Output:
2014-07-16 11:00:00
You can simple use:
$time = date("Y-m-d H:i:s");
or even better use mysql NOW() function
you have to specify timezone as follows.
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());
echo $date;
The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions.
you can use mysql function
now()
You are looking for
$time = strftime('%Y-%m-%d %H:%M:%S', time());
from the documentation
%S Two digit representation of the second
%M Two digit representation of the minute 00 through 59
Also, what PHP version are you using? %i:%s should not be 00:00
I'm trying to format a SQL timestamp in PHP based on the following conditions, but can't figure out how. Can anyone point me in the right direction?
If the timestamp was TODAY, display as 4:15PM or 12:30AM
If the timestamp was before TODAY but in the past 7 DAYS, list as 'Sunday' or 'Monday'
If the timestamp was before 7 DAYS ago, list as 'mm/dd/yy'
How would I go about that?
First you need to convert the MySQL time to a unix timestamp which is what most of php date functions use. If you are using MySQLs DateTime type, you can perform the conversion in SQL with the MySQL function unix_timestamp() mysql date functions. Or you can convert the mysql date to a unix timestamp in PHP with the strtotime($mysqlDateTime) function php strtotime function
once you have the unix timestamp of the time you would like to format, the conversion would look something like this (86400 is number of seconds in 24 hours):
function displayDate($timestamp)
{
$secAgo = time() - $timestamp;
// 1 day
if ($secAgo < 86400)
return date('h:i:A', $timestamp);
// 1 week
if ($secAgo < (86400 * 7))
return date('l', $timestamp);
// older than 1 week
return date('m/t/y', $timestamp);
}
This method has the benefit of not requiring extra object creation in PHP (a tad slow) or performing unnecessary calculations on the SQL server. It might also help to know that MySQL's timestamp type stores data as a unix timestamp (number of seconds since Jan 1 1970) value requiring only 32bits for storage compared to datetime which uses 64bits of storage. 32 bits should be enough for everyone, until 2038 or something....
you can check date difference by by diff() of PHP or by msql datediff()
http://www.php.net/manual/en/datetime.diff.php
Then check difference is zero or equal to 1 or greater than 7
h 12-hour format of an hour with leading zeros 01 through 12 date('H:i:s')
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
G 24-hour format of an hour without leading zeros 0 through 23
USE DATE(G) to find AM or PM
if($TODAY)
date('h:i:s')PM
ELSE IF ($THISWEEK)
l (lowercase 'L') A
full textual representation of the day of the week Sunday through Saturday
ELSE IF($BEFOREONEWEEK)
date('d-m-y')
http://php.net/manual/en/function.date.php
This should work. Hope so :-)
You just have to use a conditional:
$now = new DateTime("now");
$ystrday = new DateTime("yesterday");
$weekAgo = new DateTime("now")->sub(new DateInterval('P7D'));
$inputDate = new DateTime(whenever);
if($yesterday < $inputDate and $inputDate < $now){
$outDate = date('g:ia', $inputDate->getTimestamp() );
}else if($weekAgo < $inputDate and $inputDate < $now){
$outDate = date('l', $inputDate->getTimestamp() );
}else if($inputDate < $weekAgo){
$outDate = date('d/m/y', $inputDate->getTimestamp() );
}
This hasn't been tested and you'll need to get your mySql date into a php DateTime object but it should get you pretty close.
I assume you're talking about the MySQL TIMESTAMP datatype, since I don't think MySQL actually has a datatype like a Unix timestamp (i.e. seconds since epoch), so you'll have to first convert the date you get using the strtotime function:
$timestamp = strtotime($dbTimestamp);
This will return a Unix timestamp you can play with.
Next we'll define a couple more timestamps to compare this value against:
First, we want to know the timestamp for midnight this morning. For that, you'll pass the string "today" to strtotime:
$today = strtotime("today");
Next, we need to know the timestamp for seven days ago. You'll have to choose between "1 week ago" and "1 week ago midnight". The difference between these two is that midnight will return the timestamp for 12am on that day, while the version without it will return the current time, seven days ago (e.g. today, the difference would be that midnight will return 12 AM on April 7 and the non-midnight version would, right now, return 3:45PM on April 7):
$weekAgo = strtotime("1 week ago midnight");
(Note, there are many formats that strtotime understands, including many relative formats like the "today" and "1 week ago" examples used above.)
Next, we need to define the date formats to use in each case:
$timeOnly = "g:i A"; // This gives an "hour:minute AM/PM" format, e.g. "6:42 PM"
$dayOfWeek = "l" // Gives a full-word day of the week, e.g. "Sunday"
$mdy = "m/d/Y" // gives two-digit month and day, and 4-digit year,
// separated by slashes, e.g. "04/14/2011"
Finally, we just do our comparisons, and format our timestamp using the date function:
if ($timestamp >= $today) {
$date = date($timeOnly, $timestamp);
} elseif ($timestamp >= $weekAgo) {
$date = date($dayOfWeek, $timestamp);
} else {
$date = date($mdy, $timestamp);
}
This will leave you with a string variable called $date which contains your database-provided timestamp in the appropriate format, which you can display on your page as needed.
How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?
The format of time stamp is like
2009-12-05 10:35:28
I want to calculate how many minutes have passed.
How to do it?
To do this in MySQL use the TIMESTAMPDIFF function:
SELECT TIMESTAMPDIFF(MINUTE, date_lastaccess, NOW()) FROM session;
Where session is the table and date_lastaccess is a DATE / DATETIME field.
If you don't wanna add a library, you can do this pretty easily:
<?php
$date1 = "2009-12-05 10:35:28";
$date2 = "2009-12-07 11:58:12";
$diff = strtotime($date2) - strtotime($date1);
$minutes_passed = $diff/60;
echo $minutes_passed." minutes have passed between ".$date1." and ".$date2;
?>
Check out some pretty date libraries in PHP. Might have something for you. Here's one : http://www.zachleat.com/web/2008/02/10/php-pretty-date/
strtotime("now") - strtotime("2009-12-05 10:35:28")
That will get you seconds difference. Divide by 60 for minutes elapsed. If you have any information on the time zone of the initial timestamp, however, you'd need to adjust the "now" to a more comparable time
something like that
$second = strtotime('now') - strtotime($your_date);
$minute = $second / 60;
strtotime return the number of seconds since January 1 1970 00:00:00 UTC, so you can easily manipulate this. if you need don't want to have 35.5 minute you can use floor to round up the number. Last remark both time need to be in the same timezone or you are going to count the timezone difference also.
You could just use
$timestamp = time();
$diff = time() - $timestamp
$minutes = date( i, $diff );
function timeAgoMin($timestamp){
if(!is_int($timestamp)){
$timestamp = strtotime($timestamp);
}
return ((time() - $timestamp) / 60);
}