How to add +9 hours on my jQuery script? - php

How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.
I create the unix timestamp in a php file doing
$end = mktime(16, 54, 0, 8, 18, 2011);
and the copy it below
Countdown Script
<script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);
$(document).ready(function() {
$("#time").countdown({
date: end_date,
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>

Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:
// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');
and:
// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)
Edit:
Since the OP said he wanted to use a TS from DB, here's the relevant code:
$date = strtotime('+9 hours', (int)$db_time);
Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:
$db_time = strtotime($db_time);
However, I urge you to check for alternative ways to parse the time.

I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.
Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)
The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.
Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):
$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();
Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:
var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );
Now the timer will fire at the correct time regardless of what time the user's clock is set to.

var end_date = new Date((<?php echo $end; ?>+32400)*1000);

end_date = end_date + ((3600*1000)*9);

mktime returns seconds, so you simply add the desired amount of seconds
using the end_date created with php, add this line:
end_date+=9*60*60

Call this before your countdown:
end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();
EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.
EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).

Related

How to get the duration of an inserted time by inserting another one with minute:seconds:milliseconds?

I am making a game mode in which I am trying to get the time a player has arrived at their destination after starting the mode and to do this I am using the insert of a date when it starts the mode it inserts a date and after reaching the your destination it registers another date and with both dates it calculates the time it took to get to the destination, with this I'm using date H:i:s (hours, minutes, seconds) but I need to take the time out and leave milliseconds after seconds example: i:s:u (minutes, seconds, milliseconds) but I'm not able to do this, I've tried it in several ways, basically everything works as follows:
1. I add in the player array a current date with hour, minutes, seconds;
$this->game[$player->getName()] = ["start" => strtotime('now')];
2. After the Player arrives at his destination he calculates the time of his trajectory creating another current date with already registered and using date and mktime to do the join and give a visual of time to the player;
$time = date('H:i:s', mktime(0, 0, str_replace("-", "", $this->game[$player->getName()]["start"] - strtotime('now'))));
3. Send the pretty message to the player about the time of his trajectory then time will be something like this: 01:45:23 (minute:seconds:milliseconds).
$player->sendMessage("You beat your time record by ".$time);
This is my method of doing, if you have another better method with the milli seconds added I accept the suggestion! Maybe there might be some errors in my code that I'm still not sure if they work correctly as the subtraction to calculate and join the current time with the previous one, tell me if it's right and if it is not correct correct me or do better. Thank you
Use microtime which returns the current Unix timestamp with microseconds
$game = [];
$game['start'] = microtime(true);
// Do stuff
sleep(3); // Without the sleep, start and end are the 'same'
$game['end'] = microtime(true);
$elapsedTime = ($game['end'] - $game['start']);
$minutes = floor($elapsedTime / 60);
$seconds = $elapsedTime % 60;
$milliseconds = number_format($elapsedTime - floor($elapsedTime),3);

php add scheduled tasks as minutes to current time as 12:10 - 12:19

I´m making a simple time management system feature and I want to add
task and estimated minutes.
So if I add into the field "finish sending e-mail to John" and "23" (as minutes) it goes into
mysql as $sql = "INSERT INTO schedule (task, time, timestamp) VALUES ('$_POST[task]','$_POST[time]','$_POST[timestamp]')";
The output would be " Finish sending e-mail to John 21:02 - 21:25 "
so if next task takes 7 minutes it will be from 21:26 - 21:33" (take notice
of the first task and so and and so forth
I tried echo date('H:i', strtotime('+["time"] minutes', ));
but it doesn´t
work and I don´t know how the next record would take notice of the next one
is this possible?
What you tried above is almost correct, except that you might mean $_POST['time'] instead of ["time"], making your code: echo date ('H:i', strtotime('+{$_POST["time"]} minutes'));. But that will give you the time minutes after current time, not after the starting time.
To get the end time, you need to convert your start time (I assume it's $_POST['timestamp']) into UNIX timestamp, then add the task's length and get the UNIX timestamp from it.
Give this a try:
// Remember to check for valid user input. I'll leave that for you.
$task = $_POST['task'];
$time = $_POST['time'];
$timestamp = $_POST['timestamp'];
// Get the time here
$start_time = date ("H:i", strtotime ($timestamp));
$end_time = date ("H:i", strtotime ($timestamp) + $time * 60);
echo "{$task} {$start_time}-{$end_time}\n";

PHP scheduled email alerts using preselected timezone

I've been searching alot and I can't seem to find a solution.
I have a PHP web page where I can schedule email alerts at specific times. I select the date and time of when the alert is to be sent. This is stored in MySQL table in UNIX format. I have a job that executes every 15 minutes and sends the emails if the date+time is in the past - this all works perfectly except I need to extend it for my USA colleagues. I am based in Ireland so I will need to manage the different timezones all across the US. I am planning on adding a select list of timezones that the user will have to select once they register...at least thats a start. Managing timezones is fine because I reckon all I need to do is minus the time different from the server time and then save the date time in unix format. DST is a different issue tho - does anyone have any ideas on how to overcome this?
I have read that using UTC as the base time but even if that is the case wont I still have the same issue?
Thanks a mil!
Your times are already in UNIX timestamp format so all you need is to calculate time difference (offset) of user. For example Ireland is in UTC/UTC+1 timezone. So all you need is to do the math like james_t mentioned in his comment. If you need user from Ireland to get an email in 9:00pm UTC+1 you have to send it in 8:00pm UTC. So what's an idea?
Allow users to select timezone which means they select offset from UTC. Keep it somewhere in database (your users table or some other table, doesn't matter).
Convert offset in seconds:
$delta_time = -1 * $offset * 3600
Then calculate your trigger-time:
$trigger_time = time() + $delta_time;
Now you have time when your email sender can fire in right moment depending on user's timezone settings.
For example:
$offset = 1; // summer in Ireland
$server_time = time(); // at the moment 1350509127
$delta_time = -1 * $offset * 3600; // -3600
$trigger_time = $server_time + $delta_time; // 1350505527
All you need is to compare $trigger_time with UNIX timestamp from your database and decide to send an email (or not).
Ofc, it's not bad idea to use PHP timezones instead of pure +/- offset and stay updated when DST changes apply on certain locations.
Make some test, this is not that hard.
This is just a general idea, not complete working solution.
Update:
To calculate time-difference in seconds between any two timezones you can use something like this:
function delta_offset()
function delta_offset($server_timezone, $user_timezone) {
$dt = new DateTime('now', new DateTimeZone($server_timezone));
$offset_server = $dt->getOffset();
$dt->setTimezone(new DateTimeZone($user_timezone));
$offset_user = $dt->getOffset();
return $offset_user - $offset_server;
}
To get an offset in seconds:
$server_tz = "Europe/London";
$user_tz = "America/New_York";
$offset = delta_offset($server_tz, $user_tz); // offset in sec.
Create some output:
$dt = new DateTime('now', new DateTimeZone('UTC'));
echo "<pre>UTC date/time: " . $dt->format('l, F jS, <b>H:i:s</b>') . "\n";
$dt = new DateTime('now', new DateTimeZone($server_tz));
echo "London date/time: " . $dt->format('l, F jS, <b>H:i:s</b>') . "\n";
$dt = new DateTime('now', new DateTimeZone($user_tz));
echo "New York date/time: " . $dt->format('l, F jS, <b>H:i:s</b>') . "\n\n";
echo "Time difference between London (UK) and New York (USA) is: <b>$offset_h</b> ($offset s)</pre>";
Output in browser (in moment of writing this post):
UTC date/time: Wednesday, October 17th, 22:32:27
London date/time: Wednesday, October 17th, 23:32:27
New York date/time: Wednesday, October 17th, 18:32:27
Time difference between London (UK) and New York (USA) is: -5:00 (-18000 s)
In this case offset is -5 hours (-18000 seconds) but it automatically changes if DST rules change for any of timezones given as function-arguments.
Delta-offset provides information how much earlier or later you have to send an email to user in different timezone and all you need now is to do simple +/- delta-offset with your email-sender's scheduler.
Hope this may help you to get right solution for your problem.
Update #2 - Example (theory)
Imagine this situation.
Your current server-time is X and its 7:00pm at the moment in Ireland. I live in Serbia and we have same DST rules but I’m one hour after (UTC+1/UTC+2). Difference between your and my time is +3600 seconds (1 hour).
Now you have to send an email to me in 10:00pm (it’s 9:00pm in Ireland).
Current time is X.
Delta-offset is -1 * +3600 = -3600 (delta-offset multiplied with -1).
Sending time on your location in 10:00 pm is X + 10800 (3 hours later).
Sending time on my location in 10 pm is X + 10800 + delta-offset = X + 7200 (2 hours later).
Formula to check if actual time is equal or greater than trigger-time (sending time) is:
current_timestamp >= trigger_timestamp + delta_offset
where delta-offset from delta_offset() function must be multiplied with -1 to use in formula.
Now you can send email when you want and be sure it will be sent using user's local time (ofc, if user timezone settings are correct).
Note: Difference from this example (Serbia - Ireland = +1 hour) is different during DST changes which means that 1 hour every year we're in same timezone (0 delta-offset), and one hour we have +2 hours delta-offset. This is possible because DST changes are applied 1 hour earlier in Serbia so when our time is changed +1 you have to wait 60 minutes before same change applies to Ireland-time *then we're +2) and same thing when we bring back clock to normal time (0 difference).

Static countdown with javascript/php, how?

var austDay = new Date("May 18, 2012 00:00:00");
$('#countdown').countdown({until: austDay});
Is what I got. I wish to make this static, which I mean by it shows the same countdown in all timezones. So no matter if you change your timezone or your date on your pc, it should not affect the countdown and it should still be e.g 8 hours left.
Maybe this is not possible because Javascript is Client side?
What can I do? I really want it to live countdown and not so you need to refresh. Maybe I can use some help from PHP?
The countdown should be the same for example 4 hours left, it should also display that in new york and asia..
You can use PHP to pass the server time to the client like so.
var time = new Date(<?php echo time()*1000; ?>);
var austDay = new Date("May 18, 2012 00:00:00");
This creates a date object with the date and time shown, in the user's local timezone. To create a UTC date, you can do something like this instead:
var austDay = new Date(Date.UTC(2012, 4, 18));
...where 4 is the zero-based month number (2012 and 18 are the year and day, obviously).
If you need to display the date afterwards, use the "UTC" functions instead of their non-UTC counterparts, for example:
console.log(austDay.toUTCString()) // "Fri, 18 May 2012 00:00:00 GMT"
Another problem is that users could change their clocks. To give them something like "8 hours left" and be absolutely sure, you'd have to compare the server time to the client's time and set the date based on that.
For example, if the server knows that the thing happens at noon tomorrow, and it's 9:00 at night, then the countdown ends in 15 hours. You can tell the client how much time is left until the countdown is ready instead of passing them an absolute time.
var austDay = new Date();
var hoursLeft = <?php echo $something ?>;
austDay.addHours(hoursLeft);
You'd probably want to do it in seconds or smaller instead of hours, I used hours here for simplicity.

How to display local time with PHP

Our server is set to GMT time so the hour does not keep jumping around in spring and autumn. However, during summer time, it is annoying that all the times are displayed an hour out.
How do I get and display the time, taking into account the local timezone in PHP (especially when the server thinks the local timezone is GMT).
or, How do I know if an area is using "summer time" at the moment?
or, How do I display a GMT time stamp or a different timezone?
Actually, I think I may have found the answer I need...
date_default_timezone_set()
// Sets the default timezone used by all date/time functions in a script
The PHP manual entry is here:- http://us2.php.net/manual/en/function.date-default-timezone-set.php
You could add this line in PHP:
putenv("TZ=US/Eastern");
And every subsequent call to time()/date() will give you the time in your time zone.
List of time zones
This code will display the current time in the Eastern time zone (US):
putenv("TZ=US/Eastern");
date("h:i:s")
You can use the date function to offset GMT
Easiest way to display local time is to use JavaScript:
<?php
// Get unix time from database
$seconds = .....;
?>
<html>
<head>
<script type="text/javascript">
function showLocalTime()
{
var seconds = <?=$seconds;?>;
var date = new Date(seconds*1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
document.getElementById("local_time").innerHTML = "Local Time: " + formattedTime;
}
</script>
</head>
<body onload="showLocalTime()">
<h2 id="local_time"> Local Time: </h2>
</body>
</html>
get the date/time and first check to see if the month (split on dashes if its a DATETIME field) is a 'summer month', or a month that will cause the time to be an hour out.
If so, convert it to a unix timestamp. Then, add (or minus, whichever way it is out) 60 * 60 (60 mins) to the timestamp and convert into a human readable format.
Problem solved!

Categories