How to turn php time function into javascript function? - php

I'm not that good at javascript (yet), so I need some help, with an alternative version of this php script (In javascript)
function until($format = ""){
$now = strtotime("now");
$nextTuesday = strtotime("-1 hour next tuesday");
$until = $nextTuesday - $now;
if(empty($format)){
return $until;
}else{
return date("$format",$until);
}
}
Just need it to count down, until next tuesday, in a really short way (Not in 20+ lines, like all the other script I've seen)
It should still return a timestamp, if it's possible (Need it for an offline app)
So if anyone could help me, I would be really happy (Not that I'm not happy right now, but I would be even happier) :D

You may want to take a look at the phpjs site. They have code showing how a substantial number of PHP functions can be done in JS.
Specifically: strtotime and date

JS doesn't have anything remotely close to strtotime. You'd have to determine "next tuesday" yourself. Once you've got that, you can extract a timestamp value using .getTime(), which will be the number of milliseconds since Jan 1/1970. This value can also be fed back into a new date object as a parameter, so you can do date math using simple numbers externally, then create a new date object again using the result.
e.g.
var now = new Date();
var ts = now.getTime();
var next_week = ts + (86400 * 7 * 1000);
next_week_object = new Date(next_week);
Once you've got the "next tuesday" code figured out, the rest is trivial

To get milliseconds till the next tuesday (nearest in the future):
function f_until(){
var now = new Date(Date.now());
var nextT = new Date(Date.now());
var cD = nextT.getDay();
if(cD < 2)nextT.setDate(nextT.getDate() + (2-cD));
else nextT.setDate(nextT.getDate() + (9-cD));
nextT.setHours(nextT.getHours() - 1);
//alert('next tuesday: '+nextT.toString());
return nextT.getTime() - now.getTime();
}

Related

How to use offsets for time zones with php?

I just don't understand GMT on how it works with your php sql server time. How do you relate to your database with the minutes offset? So if this produces -420 minutes how do we relate that to our database time (for example unix time 2016-09-14 22:40:31)(your NOW() time)?
I am just not sure how to implement this in PHP? There is some vague information I have found on how to use it after you get your minutes offset.
`date_default_timezone_set('America/Boise');`
$created=date('Y-m-d H:i:s');
I got the code below from:
https://stackoverflow.com/a/5492192/6173198
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
//go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
//To ignore daylight saving time look for the lowest offset.
//Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
alert(TimezoneDetect());
You can use the bellow code to set the time zone:
date_default_timezone_set('Europe/London');
This code will add +1 hour onto the timestamp.
$timestamp= strtotime("+1 hour");
I hope this is what you were asking for.
You can also use the same as what you were using to turn the timestamp into text:
gmdate("H:i", $timestamp);

Working with UTC and php

I'm using Live Connect to create calendar events. According to their docs, the start_time given for an event should indicate how many hours off the time is from UTC (i.e. +0700 or -0300). As a first stab , I've got some code that works, pieced together from the php manual. However, it "feels" pretty verbose. So, from a stylistic point of view, might there be a way to clean up what I've got into something more succinct? Note that the $time_zone is something that I know based on a given user.
$dateTimeZone = new DateTimeZone($time_zone);
$dateTime= new DateTime("now", $dateTimeZone);
$gmt_offset = ($dateTime->getOffset())/3600;
$negative = ($gmt_offset<0);
$gmt_offset = abs($gmt_offset);
if ($gmt_offset < 10) {
$gmt_offset = '0'.$gmt_offset.'00';
} else {
$gmt_offset = $gmt_offset.'00';
}
if ($negative) {
$gmt_offset = '-'.$gmt_offset;
} else {
$gmt_offset = '+'.$gmt_offset;
}
Thank you for your input.
-Eric
$gmt_offset = $dateTime->format('O');
From the PHP manual page for date():
format character: O
Description: Difference to Greenwich time (GMT) in hours
Example returned values: Example: +0200

Elapsed time from a given time in the database

I have a HTML table which has records pulled in from the database. I'm using PHP/MySQL.
The Column in my table named "Timer" is not retrieved from the database. I need the elapsed time (from the a specific time in the database) to be shown here. For Example, let's say the time now is 21 Feb 2013 6.20 pm and the time in the database is 21 Feb 2013 5.50 pm, I need the Timer Column to Display 00:30:00 (as thirty minutes have passed since 5.50PM). It must be a Running timer (Not a static one which can be computed by using MySQL datetime difference) so whoever accesses the page should be able to see the same elapsed time. I also need to stop the timer when I click another button.
I saw other posts here related to this question like this Elapsed Time to database from Javascript timer but I think what I'm asking is different. I'm still confused on how to go about doing this. I've very little Javascript knowledge, would be greatful if you could help me with it or refer me to the right place. Thank you!
This can be achieved with very little Javascript.
Assuming that the "Created" time is rendered dynamically in the table with format dd MMM yyyy hh:mm:ss, something like this should do the trick:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).text());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed", 2);
timeLogger.start();
$("#stop_timer").click(function() {
timeLogger.stop();
});
$("#start_timer").click(function() {
timeLogger.start();
});
});
</script>
</head>
<body>
<table border="1">
<tr><th>Created</th><th>Timer</th></tr>
<tr><td id="date">21 Feb 2013 12:30:00</td><td id="elapsed"></td></tr>
</table>
<input id="stop_timer" type="button" value="Stop timer"></input>
<input id="start_timer" type="button" value="Start timer"></input>
</body>
</html>
Copy the code above into a file, say index.html, and open it in a browser. I tested it on Chrome.
It should update the elapsed time every 2 seconds, but you may change the update interval to something that suits you, e.g. to make it update every 5 minutes:
new ElapsedTimeLogger("#date", "#elapsed", 300);
The general concept is to parse the rendered "Created" date into an epoch timestamp (in milliseconds) and then compute its difference with the current system time. To get the elapsed time updating dynamically you use Javascript's setInterval function. To stop updating the elapsed time use Javascript's clearTimeout function.
I lifted the prettyPrintTime function from powtac.
If you are looking for a pure html base solution with the sql to do the dynamic changes, it is impossible. If you need to do a running timer you will need to use JS. (can be done with the help of css5 as well).
You'd want to use PHP to retrieve the time from the database, then use Javascript to display a timer that's counting from the time retrieved. You should be able to find available premade Javascript scripts that can do this quite easily. Here's one I found. I have no idea if it's the best for your needs, but it was amongst the first results. Just snip off the parts not needed, like the year, month, etc.
http://praveenlobo.com/techblog/javascript-countup-timer/

Determining whether the current time is before 5pm that day

I want to have code in a loop that only runs if it is before 5pm on any day.
What code would do this?
IF (current_time < 5:00pm) {
// Do stuff
}
This solution uses the nice PHP5 DateTime class, and avoids the clunky old strtotime() function:
$hoursNow = new DateTime()->format('H');
if($hoursNow < 17) {
....
}
Simple one that gets the job done:
if (date('H') < 17)
{
// DO SOMETHING
}
Just remember that this date comes from the server. So, if the client is in another timezone, that may not work as required. The good thing about this, is that the user can't change his computer date in order to trick the site into something.
And if you want to do that with javascript (where the value will come from the user's computer), just do the following:
var today = new Date();
if (today.getHours() < 17)
{
// DO SOMETHING
}
if(time() < strtotime('today 05:00 pm')) {
// Do stuff
}
In short...
$t = time(); # or any other timestamp
if (date('H', $t) < 17) {
// Do stuff
}
Works for any day
Note: Make sure your timezone is correct (check php config or just use date_default_timezone_set function before calling date function)

Getting unix timestamp in milliseconds in PHP5 and Actionscript3

In Actionscript, the Unix timestamp in milliseconds is obtainable like this:
public static function getTimeStamp():uint
{
var now:Date = new Date();
return now.getTime();
}
The doc clearly states the following:
getTime():Number Returns the number of
milliseconds since midnight January 1,
1970, universal time, for a Date
object.
When I trace it, it returns the following:
824655597
So, 824655597 / 1000 / 60 / 60 / 24 / 365 = 0.02 years.
This is obviously not correct, as it should be around 39 years.
Question #1: What's wrong here?
Now, onto the PHP part: I'm trying to get the timestamp in milliseconds there as well. The microtime() function returns either a string (0.29207800 1246365903) or a float (1246365134.01), depending on the given argument. Because I thought timestamps were easy, I was going to do this myself. But now that I have tried and noticed this float, and combine that with my problems in Actionscript I really have no clue.
Question #2: how should I make it returns the amount of milliseconds in a Unix timestamp?
Timestamps should be so easy, I'm probably missing something.. sorry about that. Thanks in advance.
EDIT1: Answered the first question by myself. See below.
EDIT2: Answered second question by myself as well. See below. Can't accept answer within 48 hours.
I used unsigned integer as the return type of the function. This should be Number.
public static function getTimeStamp():Number
{
var now:Date = new Date();
return now.getTime();
}
Think I got the function for getting milliseconds in PHP5 now.
function msTimeStamp() {
return round(microtime(1) * 1000);
}
For actionscript3, new Date().getTime() should work.
In PHP you can simply call time() to get the time passed since January 1 1970 00:00:00 GMT in seconds. If you want milliseconds just do (time()*1000).
If you use microtime() multiply the second part with 1000 to get milliseconds. Multiply the first part with 1000 to get the milliseconds and round that. Then add the two numbers together. Voilá.
Use this:
intval(microtime(true)*1000)
To normalize a timestamp as an integer with milliseconds between Javascript, Actionscript, and PHP
Javascript / Actionscript:
function getTimestamp(){
var d = new Date();
return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()).valueOf();
}
PHP:
function getTimestamp(){
$seconds = microtime(true); // true = float, false = weirdo "0.2342 123456" format
return round( ($seconds * 1000) );
}
See PHP note at "ben at sixg dot com's" comment at: http://www.php.net/manual/en/function.gmmktime.php
EXCERPT:
For most intents and purposes you can imagine that mktime() first converts your input parameters to GMT and then calls gmmktime() which produces a GMT timestamp.
So, time() always will return the same thing at the same actual moment, anywhere in the world.
gmmktime() and mktime(), when given specific time parameters, convert those time parameters FROM the appropriate timezone (GMT for gmmktime(), local time for mktime()), before computing the appropriate timestamp.
UPDATE:
On some versions of PHP, the timestamp with milliseconds is too large to display as a string. So use the sprintf function to get the string value:
PHP
function getTimestamp($asString=false){
$seconds = microtime(true); // false = int, true = float
$stamp = round($seconds * 1000);
if($asString == true){
return sprintf('%.0f', $stamp);
} else {
return $stamp;
}
}
microtime() in php5 returns unix timestamp with microseconds as per microtime() and if the get_as_float argument is not provided, it gives you a string formatted as "msec sec" so the first part is the millisecond part and the second is the second part. Just split it in two and you get the two parts of the timestamp
Simple answer for PHP:
function exact_time() {
$t = explode(' ',microtime());
return ($t[0] + $t[1]);
}
To get millisecond timestamp from PHP DateTime object:
<?php
date_default_timezone_set('UTC');
$d = new \DateTime('some_data_string');
$mts = $d->getTimestamp().substr($d->format('u'),0,3); // millisecond timestamp
PHP 7
This function has its return type declared.
function timestamp_ms(): int {
$times = gettimeofday();
$seconds = strval($times["sec"]);
$milliseconds = strval(floor($times["usec"]/1000));
$missingleadingzeros = 3-strlen($milliseconds);
if($missingleadingzeros >0){
for($i = 0; $i < $missingleadingzeros; $i++){
$milliseconds = '0'.$milliseconds;
}
}
return intval($seconds.$milliseconds);
}
PHP 5
function timestamp_ms() {
$times = gettimeofday();
$seconds = strval($times["sec"]);
$milliseconds = strval(floor($times["usec"]/1000));
$missingleadingzeros = 3-strlen($milliseconds);
if($missingleadingzeros >0){
for($i = 0; $i < $missingleadingzeros; $i++){
$milliseconds = '0'.$milliseconds;
}
}
return intval($seconds.$milliseconds);
}
when you need the millisecond in str format, I think you should use:
public function get_millisecond() {
list($milliPart, $secondPart) = explode(' ', microtime());
$milliPart = substr($milliPart, 2, 3);
return $secondPart . $milliPart;
}
this will fix the bug int some get millisecond example where the milli part is like : 0.056. some example convert the milli part to float, your will get 56 instead of 056. I think some one want 056.
especially when you need the millisecond to order some data.
hope will help. :)
I recently had this problem to get a timestamp in milliseconds. To just multiply the unix timestamp by 1000 did not resolve the problem because i had to compare two database entrys very precicely. Aparently the php datetime object can´t handle milliseconds/microseconds but its stored in the datetime string anyway. So here is my solution:
$dateObject = new \DateTime('2015-05-05 12:45:15.444', new \DateTimeZone('Europe/London'));
$millis = $dateObject->format('v');
echo $dateObject->getTimestamp()*1000+$millis;
This should also work with microseconds if you use format->('u') (and of course multiply the timestamp by 1000000) instead. I hope you find this useful.
Something like this:
$mili_sec_time = $_SERVER['REQUEST_TIME_FLOAT'] * 1000;
Gives float type representing miliseconds from UNIX epoch to starts of the request.
$timestamp = str_replace(".","",number_format((float)microtime(true),2,'.',''));

Categories