Want to display the current date/time - php

Hi I'm using php and sql through odbc to write a program and i hav got abit stuck in a part where i want to display the current date/time in the format date('Y-m-d H:i:s) but it only displays the gmt time. I want to add 8hours to it.Can any of you b able to help me.Thank you so much

Check out date_default_timezone_set. You can do something like:
date_default_timezone_set('America/Los_Angeles');
print 'Current datetime is: ' . date('Y-m-d H:i:s');
You could use that to set the timezone to whatever timezone you need time to be at, and then use date normally. Alternatively, you can do this, using strtotime:
print 'Current datetime is: ' date('Y-m-d H:i:s', strtotime('+8 hours'));

If you're looking for a way to display a timestamp in a user's local time, you can use JavaScript:
function showtime(t)
{
if (t == 0)
{
document.write("never");
return;
}
var currentTime = new Date(t);
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
document.write();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
document.write(month + "/" + day + "/" + year + " " +
hours + ":" + minutes + ":" + seconds + " ");
if(hours > 11){
document.write("PM");
} else {
document.write("AM");
}
}
Then if you need to display a time, just make a call to it in the HTML and splice in the value from PHP:
<script type="text/javascript">showtime(<?=$time."000"?>)</script>

I would steer clear of the timezone method.
If i understood correctly, you want to add time, thus change it. An example could be, A task has been created NOW, and must be complete in 8 hours. The timezone method would only change the display of the date and time. Only change the timezone setting if you know your visitor's timezone, and datetime's must be shown relative to them.
Now: 1234418228 is 2009/02/12 00:57:08 in Montreal or 2009/02/11 09:57:08 in San Francisco. It's the exact same moment.
Appending to the first answer, date() and strtotime() are your friends.
strtotime( "+8 hours", $now )
$now being a timestamp of when it's supposed to relate to. So if your start time isn't time(), you can still use that. eg
strtotime( "+8 hours", strtotime( "2009/03/01 00:00:00" ); (8AM on 2009/03/01)
However, when dealing with intervals counted in weeks, or less, i prefer doing it 'mathematically'
$StartTime = strtotime( "2009/03/01 13:00:00" );
$EndTime = $StartTime + ( 8 * 60 * 60 );
date( "Y/m/d H:i:s", $EndTime ) ==> "2009/03/01 21:00:00"
3600 seconds in an hour, 86400 in a day.
You can't use this method for months, quarters or years because the number of seconds they last varies from one to the next.

If you want to use time for a certain timezone, then using date_default_timezone_set() is preferred. anyway you can provide the date() function another parmater: int timestamp. an integer representing the timestamp you would like date() to return the information about.
so if you would like to show date('Y-m-d H:i:s') for now you can use this:
$now = date('Y-m-d H:i:s', time() ); // time() returns current timestamp.
// if you omit the second parameter of date(), it will use current timestamp
// by default.
$_8hoursLater = date('Y-m-d H:i:s', time()+60*60*8 );
$_8hoursBefore = date('Y-m-d H:i:s', time()-60*60*8 );

Related

PHP Adding 15 minutes to Time value

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));

How to convert date into same format?

I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.

check time for time difference in 24hr

In php i get the variable $date_time in this format -- 11-01-2010 20:48:25 . This time is GMT time. I have a 2 hour flexibility and if it exceeds 2 hours then i have to reject it. I am set in EST, but i want to do the check based on GMT only so that there is no errors in the time difference. How can i set to GMT in my php code and how do i check for the 2 hours flexible time difference? like for this example it is acceptable for any time between 11-01-2010 18:48:25 and 11-01-2010 22:48:25. Also will it be an issue if $date_time is 11-01-2010 23:48:23?
Clarification
I am doing a $date_time=$_GET['date_time'];. Then i need to check if this new $date_time if within 2 hours range of the current GMT time. if it is in the range, then i will proceed to execute that code, else i will show an error or do something else. I wanted to know how i am going to check this 2 hours range for this $date_time variable.
Here is a way how to convert your time format into a UNIX timestamp:
$date = strptime($date_time, "%m-%d-%Y %T");
$ut = mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], 1 + $date['tm_mon'], $date['tm_mday'], 1900 + $date['tm_year']);
$now = time();
if($ut >= $now && $ut <= ($now + 7200)) { // 7200 = 2 * 60 * 60 seconds
// allowed
}
Reference: strptime, mktime, time.
Note: time() always returns the UNIX timestamp in UTC (regardless of time settings). So this assumes that the $date_time timestamp is a GMT time.
Working example (of course you have to provide a valid GMT time for $date_time).
Note 2: If the input time is not in GMT, you can set the timezone with date_default_timezone_set (affects mktime but not time).
Working example (change time and timezone accordingly)
If PHP >= 5.3 (you've got a seriously weird format BTW):
date_default_timezone_set('EST');
$inputtime = DateTime::createFromFormat('m-d-Y H:i:s','11-01-2010 20:48:25',new DateTimeZone("GMT"));
$diff = $inputtime->getTimestamp() - time();
if(abs($diff) > 7200){
//more then 2 hours difference.
}
If you run on PHP > 5.3, you can use DateTime for this :
$my_date = "11-01-2010 20:48:25";
$date = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_upper = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower->sub(new DateInterval('PT2H'));
$date_upper->add(new DateInterval('PT2H'));
var_dump($date >= $date_lower && $date <= $date_upper); // bool(true)
I find it more readable.
You can also use another timezone if necessary, check the third argument of createFromFormat.
I suggest you to never pass times and dates with format string. Just convert it later. You just pass the timestamp as a get variable and then you format it in the script.
It's the best solution and also the cleanest.
Then use the following code:
$flexibility = X seconds;
if ($date_time < time() - $flexibility or $date_time > time() + $flexibility)
{ /*Error*/ }

How to obtain, increment, and compare datetime in PHP?

I am developing a quiz site and there is time for x min to answer the quiz. So when user clicks on start quiz link the starttime (current time at this instant) is recored in session. Also the endtime (start_time+ 30 min) is recorded in session and every time he submits a answer the current time is compared with the quiz end time. Only if the current time is less than end_time the answer should be accepted.
How can I get the currentdatetime?
How can I add x minutes to current this datetime?
How can I compare (<=) datetime ?
I think we should use date time. Is it right?
PHP measures time as seconds since Unix epoch (1st January 1970). This makes it really easy to work with, since everything just a single number.
To get the current time, use: time()
For basic maths like adding 30 minutes, just convert your interval into seconds and add:
time() + 30 * 60 // (30 * 60 ==> 30 minutes)
And since they're just numbers, just do regular old integer comparison:
$oldTime = $_SESSION['startTime'];
$now = time();
if ($now < $oldTime + 30 * 60) {
//expired
}
If you need to do more complicated things like finding the date of "next tuesday" or something, look at strtotime(), but you shouldn't need it in this case.
use php builtin functions to get time:
<?php
$currentTimeStamp = time(); // number of seconds since 1970, returns Integer value
$dateStringForASpecificSecond = date('Y-m-d H:i:s', $currentTimeStamp);
?>
for your application that needs to compare those times, using the timestamp is more appropriate.
<?php
$start = time();
$end = $start + (30 * 60); // 30 minutes
$_SESSION['end_time'] = $end;
?>
in the page where the quiz is submitted:
<?php
$now = time();
if ( $now <= $_SESSION['end_time'] ) {
// ok!
}
?>
Use the time() function to get a UNIX timestamp, which is really just a large integer.
The number returned by time() is the number of seconds since some date (like January 1, 1970), so to add $x minutes to it you do something like (time() + ($x*60)).
Since UNIX timestamps are just numbers, you can compare them with the usual comparison operators for numbers (< <= > >= ==)
time() will give you the current time in seconds since 1/1/1970 (an integer), which looks like it should be good.
To add x minutes, you'd just need to add x*60 to that, and you can compare it like any other two integers.
Source: http://us3.php.net/time
This is an old question but I wanted to provide an answer based on the PHP 5.2 DateTime class which I feel is much easier to use and much more versatile than any previous functions.
So how can i get the currentdatetime?
You can create a new DateTime object like this:
$currentTime = new DateTime();
But at this point, $currentTime is a datetime object and must be converted to a string in order to store it in a database or output it.
$currentTime = $currentTime->format('Y-m-d H:i:s');
echo $currentTime;
Outputs 2014-05-10 21:14:06
How can i add x minutes tocurrent this datetime?
You can add x minutes with the modify method:
$currentTime = new DateTime();
$addedMinutes = $currentTime->modify('+10 minutes');
echo $addedMinutes;
Outputs 2014-05-10 21:24:06
How can i comapare (<=) datetime ?
With the DateTime class, you can not only easily compare datetime objects, you can get the difference between them.
$currentTime = new DateTime('2014-05-10 21:14:06');
$addDays = $currentTime->modify('+10 days');
To compare
if ($currentTime >= $addDays) {
//do something//
}
$diffTime = new DateTime('2014-05-10 21:14:06');
$diff = $addDays->diff($diffTime);
$diff = $diff->format('There are %d days difference.');
echo $diff;
Outputs There are 10 days difference.

Adding time in PHP

I am pulling a datetime from a mysql db and i would like to add X hours to it then compare it to the current time. So far i got
$dateNow = strtotime(date('Y-m-d H:i:s'));
$dbTime = strtotime($row[0]);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
NOTE: I am using php 5.1.2 so date_add doesnt work (5.3.0)
You have quite a few options here:
1.
$result = mysql_query("SELECT myDate FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = strtotime("+4 hours", strtotime($myDate));
2.
// same first two lines from above
$fourHoursAhead = strtotime($myDate) + 4 * 60 * 60;
3.
$result = mysql_query("SELECT UNIX_TIMESTAMP(myDate) FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = $myDate + 4 * 60 * 60;
4.
$fourHoursAhead = strtotime("+4 hours", $myDate);
5.
$result = mysql_query("SELECT UNIX_TIMESTAMP(DATE_ADD(myDate, INTERVAL 4 HOUR))");
$fourHoursAhead = mysql_result($result, 0);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
strtotime has an optional second argument. Provide a Unix timestamp there and the output will be relative to that date instead of the current date.
$newTime = strtotime('+4 hours', $dbTime);
You can also use the fact that Unix timestamps are seconds-based - if you know what four hours are in seconds, you can just add that to the time integer value.
time() and strtotime() result in unix timestamps in seconds, so you can do something like the following, provided your db and do your comparison:
$fourHours = 60 * 60 * 4;
$futureTime = time() + $fourHours;
strtotime("+4 hours", $dbTime);
The second argument is the timestamp which is used as a base for the calculation of relative dates; it defaults to the current time. Check out the documentation.
Edit:
For short periods of time, max 1 week, adding seconds to a timestamp is perfectly acceptable. There is always (7 * 24 * 3600) seconds in a week; the same cannot be said for a month or year. Furthermore, a unix timestamp is just the number of seconds that have elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). That is not effected by timezones or daylight-savings. Timezones and daylight-savings are only important when converting a unix timestamp to an actual calendar day and time.
I tend to use the time() function, and this page from the manual shows them displaying the date a week in the future:
http://us3.php.net/manual/en/function.time.php
Here's how I'd do it:
Pull the time from the database using the UNIX_TIMESTAMP() function.
The UNIX timestamp is in seconds, so add 4*60*60 to it.
Convert the modified UNIX timestamp to a date using PHP's localtime() or strftime() function.
query("SELECT UNIX_TIMESTAMP(someDatetimeColumn) ...");
. . .
$dbTimeAdjusted = localtime($row[0] + 4*60*60);
Probably the safest way to do the compare is right in the SQL
SELECT * FROM my_table WHERE someDateTimeColumn < DATE_ADD(NOW(), INTERVAL 4 hour)
And since you're assembling it in PHP, you can dynamically replace the "4 hour" bit with whatever your code needs to compare.
(Note: putting the entire calculation on the other side of the comparison to the column allows MySQL to do the calculation once per query, rather than once per row, and also use the table's index, if that column has one.)
Assuming that the timestamp returned by the DB is in SQL format, the following should work fine:
$dbTime = strtotime($row[0]);
$nowTime = time();
$future_dbTime = strtotime("+4 hours", $dbTime);
$diff_time_seconds = $nowTime - $dbTime;
if ($diff_time_seconds > 0) {
echo "The current time is greater than the database time by:\n";
$not_equal = true;
}
if ($diff_time_seconds == 0) {
echo "The current time is equal to the database time!";
}
if ($diff_time_seconds < 0) {
echo "The current time is less than the database time by:\n";
$not_equal = true;
}
if ($not_equal) {
$diff_time_abs_seconds = abs($diff_time_seconds);
echo date('h:m:s', $diff_time_abs_seconds);
}

Categories