I have a report I built but the problem is the datetimes in the database for the 3 major events are the same as the system processes then so fast, there is no easy way about it as I aggregate data from 4 servers into one jquery datatable and sort by date time decending.
So my question is how can I take a variable in PHP (string of mysql format date time), and reduce it by 1 second?
dognose answer is fine. Find below a method using DateTime.
For those who are not too confident about strtotime :-)
$string = "2013-06-26 18:00:00";
$date = DateTime::createFromFormat('Y-m-d H:i:s', $string);
$date->sub(new DateInterval('PT1S'));//substract 1 sec
echo $date->format('Y-m-d H:i:s'); //print : 2013-06-26 17:59:59
Doc about "PT1S" here (this can be read as Period Time 1 second)
use date along with strtotime should do the trick:
http://php.net/manual/de/function.strtotime.php
$string = "2013-06-26 18:00:00"; //can have any (valid) format
$subSeconds = 1;
$date = date("Y-m-d H:i:s", strtotime($string . " - {$subSeconds} second"));
echo $date."<br />"; //2013-06-26 17:59:59
Related
I want to add an x number of week days (e.g. 48 weekday hours) to the current timestamp. I am trying to do this using the following
echo (strtotime('2 weekdays');
However, this doesn't seem to take me an exact 48 hours ahead in time. For example, inputting the current server time of Tuesday 18/03/2014 10:47 returns Thursday 20/03/2014 00:00. using the following function:
echo (strtotime('2 weekdays')-mktime())/86400;
It can tell that it's returning only 1.3 weekdays from now.
Why is it doing this? Are there any existing functions which allow an exact amount of weekday hours?
Given you want to preserve the weekdays functionality and not loose the hours, minutes and seconds, you could do this:
$now = new DateTime();
$hms = new DateInterval(
'PT'.$now->format('H').'H'.
$now->format('i').'M'.
$now->format('s').'S'.
);
$date = new DateTime('2 weekdays');
$date->add($hms);//add hours here again
The reason why weekday doesn't add the hours is because, if you add 1 weekday at any point in time on a monday, the next weekday has to be tuesday.
The hour simply does not matter. Say your date is 2014-01-02 12:12:12, and you want the next weekday, that day starts at 2014-01-03 00:00:00, so that's what you get.
My last solution works though, and here's how: I use the $now instance of DateTime, and its format method to construct a DateInterval format string, to be passed to the constructor. An interval format is quite easy: it starts with P, for period, then a digit and a char to indicate what that digit represents: 1Y for 1 Year, and 2D for 2 Days.
However, we're only interested in hours, minutes and seconds. Actual time, which is indicated using a T in the interval format string, hence we start the string with PT (Period Time).
Using the format specifiers H, i and s, we construct an interval format that in the case of 12:12:12 looks like this:
$hms = new DateInterval(
'PT12H12M12S'
);
Then, it's a simple matter of calling the DateTime::add method to add the hours, minutes and seconds to our date + weekdays:
$weekdays = new DateTime('6 weekdays');
$weekdays->add($hms);
echo $weekdays->format('Y-m-d H:i:s'), PHP_EOL;
And you're there.
Alternatively, you could just use the basic same trick to compute the actual day-difference between your initial date, and that date + x weekdays, and then add that diff to your initial date. It's the same basic principle, but instead of having to create a format like PTXHXMXS, a simple PXD will do.
Working example here
I'd urge you to use the DateInterface classes, as it is more flexible, allows for type-hinting to be used and makes dealing with dates just a whole lot easier for all of us. Besides, it's not too different from your current code:
$today = new DateTime;
$tomorrow = new DateTime('tomorrow');
$dayAfter = new DateTime('2 days');
In fact, it's a lot easier if you want to do frequent date manipulations on a single date:
$date = new DateTime();//or DateTime::createFromFormat('Y-m-d H:i:s', $dateString);
$diff = new DateInterval('P2D');//2 days
$date->add($diff);
echo $date->format('Y-m-d H:i:s'), PHP_EOL, 'is the date + 2 days', PHP_EOL;
$date->sub($diff);
echo $date->format('Y-m-d H:i:s'), PHP_EOL, 'was the original date, now restored';
Easy, once you've spent some time browsing through the docs
I think I have found a solution. It's primitive but after some quick testing it seems to work.
The function calculates the time passed since midnight of the current day, and adds it onto the date returned by strtotime. Since this could fall into a weekend day, I've checked and added an extra day or two accordingly.
function weekDays($days) {
$tstamp = (strtotime($days.' weekdays') + (time() - strtotime("today")));
if(date('D',$tstamp) == 'Sat') {
$tstamp = $tstamp + 86400*2;
}
elseif(date('D',$tstamp) == 'Sun') {
$tstamp = $tstamp + 86400;
}
return $tstamp;
}
Function strtotime('2 weekdays') seems to add 2 weekdays to the current date without the time.
If you want to add 48 hours why not adding 2*24*60*60 to mktime()?
echo(date('Y-m-d', mktime()+2*24*60*60));
The currently accepted solution works, but it will fail when you want to add weekdays to a timestamp that is not now. Here's a simpler snippet that will work for any given point in time:
$start = new DateTime('2021-09-29 15:12:10');
$start->add(date_interval_create_from_date_string('+ 3 weekdays'));
echo $start->format('Y-m-d H:i:s'); // 2021-10-04 15:12:10
Note that this will also work for a negative amount of weekdays:
$start = new DateTime('2021-09-29 15:12:10');
$start->add(date_interval_create_from_date_string('- 3 weekdays'));
echo $start->format('Y-m-d H:i:s'); // 2021-09-24 15:12:10
I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
Is there a way to see if ((the current time - a timestamp in a database)>10 minutes) in php? I have a row in a database called lockout. I have the following code so far:
echo $row['lockout'];//returns 2013-05-12 22:04:17
echo date("Y-m-d H:i:s")//returns 2013-05-12 22:06:32
Furthermore does anyone have any ideas why when I insert the current Timestamp in my database, it is about a half hour off, but has the right date and year?
The SQL answer could depend on which SQL technology you use. To do this in PHP rather than SQL you could use the diff() method of DateTime:
$datetime1 = new DateTime($row['lockout']);
$datetime2 = new DateTime(date("Y-m-d H:i:s"));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%i minutes');
In PHP you can use strtotime function with relative formats like - 10 minutes to get the desired Unix timestamp:
if ( strtotime('- 10 minutes') < strtotime( $row['lockout'] ) ) ...
Use the http://www.php.net/manual/en/book.datetime.php datetime class in php
This has a diff method
If your SQL dialect is MySQL use
... WHERE UNIX_TIMESTAMP(NOW())-lockout>=600 ...
or something similar in PHP.
Do this in your query:
WHERE `lockout` < DATE_SUB(NOW(), INTERVAL 10 MINUTE)
Or, if you cannot rely on MySQL's time, use
mysqli_query('
... WHERE `lockout` < DATE_SUB(FROM_UNIXTIME(' . time() . '), INTERVAL 10 MINUTE) ...
');
Or, if you are bound to date(...), use
mysqli_query('
... WHERE `lockout` < DATE_SUB(' . date('Y-m-d H:i:s') . ', INTERVAL 10 MINUTE) ...
');
You might want to compare MySQL's and PHP's timezones and your servers' ones (if MySQL and PHP live on separate hosts).
I'm using a PHP script to grab data from Active Directory using LDAP..
When I get the user values for 'lastlogon' I get a number like 129937382382715990
I've tried to figure out how to get the date/time from this but have no idea, can anybody help?
Read this comment on the PHP: LDAP Functions page.
All of them are using "Interval" date/time format with a value that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC, and a value of 0 or 0x7FFFFFFFFFFFFFFF, 9223372036854775807, indicates that the account never expires): https://msdn.microsoft.com/en-us/library/ms675098(v=vs.85).aspx
So if you need to translate it from/to UNIX timestamp you can easily calculate the difference with:
<?php
$datetime1 = new DateTime('1601-01-01');
$datetime2 = new DateTime('1970-01-01');
$interval = $datetime1->diff($datetime2);
echo ($interval->days * 24 * 60 * 60) . " seconds\n";
?>
The difference between both dates is 11644473600 seconds. Don't rely on floating point calculations nor other numbers that probably were calculated badly (including time zone or something similar).
Now you can convert from LDAP field:
<?php
$lastlogon = $info[$i]['lastlogon'][0];
// divide by 10.000.000 to get seconds from 100-nanosecond intervals
$winInterval = round($lastlogon / 10000000);
// substract seconds from 1601-01-01 -> 1970-01-01
$unixTimestamp = ($winInterval - 11644473600);
// show date/time in local time zone
echo date("Y-m-d H:i:s", $unixTimestamp) ."\n";
?>
This is the number 100-nanosecond ticks since 1 January 1601 00:00:00 UT.
System time article in Wikipedia can give you more details.
What about this:
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
EDIT ------
I just tried the following and noticed that this method wont work unless the clock on your machine is set 10 years in the future. Below is the code I used to prove the above pretty much useless unless you do more processing maybe..
$time = time();
echo date('Y-m-d H:i:s', $time);
echo "<br />";
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
In my case I'm using Pentaho. With a Modified Javascript value you can convert the values, lastLogon is the column I wanna convert from data stream:
calendar = java.util.Calendar.getInstance();
calendar.setTime(new Date("1/1/1601"));
base_1601_time = calendar.getTimeInMillis();
calendar.setTime(new Date("1/1/1970"));
base_1970_time = calendar.getTimeInMillis();
ms_offset = base_1970_time - base_1601_time;
calendar.setTimeInMillis( lastLogon / 10000 - ms_offset); //lastLogon is a column from stream
var converted_AD_time = calendar.getTime(); // now just add this variable 'converted_AD_time' to the 'Fields' as a show in the image below
I have an array of times I want to print out. I want the times that have passed lets say 12:00 clock to be 'greyed out'.
$theTime = '12:00';
if($theTime >= $time[$i])
{....}
02:30
03:50
03:20
04:50
05:45
19:45
20:00
20:50
20:55
21:25
21:30
22:00
22:45
23:55
00:50
00:55
Im doing a simple compare 12:00 a clock to each value.
The problem occurs when you change the time to after midnight for example 00:15. How can I calculate and print the list in order, when time has passed midnight?
if you pass midnight, more than one day is involved. this means that you have to include the information of day! what day is it? so in order to achieve what you want you should list/store more than just the time! if you store a datetime value, you will have no problems calculating time differences, since php will know in what order to put the times according to the day information.
for that look at the php datetime functions.
they will also help you to calculate differences!
Use unix timestamps. create a unix time stamp for midnight, and then compare all of the others to that. Then format it as a time when you print it out.
(A while since I used PHP, so can't remember quite how to do it, but should be simple. I know I have done something similar before. Take a look at http://php.net/time, http://php.net/manual/en/function.mktime.php and http://php.net/manual/en/function.date.php. Should be simple enough =)
As Svish said, you should use real timestamps, and you should also check the date change... here the, I think, more quick and easy way to know difference between 2 time (and date) :
<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>
note the $date1 and $date2 have to be in mktime format, as :
int mktime ([ int $hour=date("H") [, int $minute=date("i") [, int $second=date("s") [, int $month=date("n") [, int $day=date("j") [, int $year=date("Y") [, int $is_dst=-1 ]]]]]]] )
I solved this problem as follows. It is not the best solution but at least it works:
$before_midnight = strtotime("23:59:59");
$before_midnight++; // this makes exact midnight
$start = strtotime("21:00");
$target = strtotime("03:00");
$after_midnight = strtotime("00:00");
for($i=$start; $i<$before_midnight; $i += 3600)
echo date("H:i", $i). "<br>";
for($i=$after_midnight; $i<=$target; $i += 3600)
echo date("H:i", $i). "<br>";
You have a string ('12:00') and are trying to compare it like a number.
http://us3.php.net/manual/en/language.operators.comparison.php
Like Svish and Paul said, you need to use integer timestamps.
$now = time(); // Get the current timestamp
$timestamps= array(strtotime('midnight'),
strtotime('07:45'),
...
);
foreach ( $timestampsas $time ) {
if ( $time >= $now ) {
// $time is now or in the future
} else {
// $time is in the past
}
}
You can format the timestamps with the date function.
Re. Svish's suggestion - strtotime() is handy for easily creating Unix timestamps relative to the current time, or any arbitrary time.
e.g. strtotime('midnight') will give you the unix timestamp for the most recent midnight.