I am looking a pure javascript which calculates date for friendly view.
eg. 05-24-2012 3:10
--> 20 minutes ago
I have a php script and I'm looking javascript version.
<?php
$time = strtotime($_GET["d"]);
echo humanTiming($time);
function humanTiming($time)
{
$time=time()-$time;
$tokens=array(31536000=>'year',2592000=>'month',604800=>'week',86400=>'day',3600=>'hour',60=>'minute',1=>'second');
foreach($tokens as $unit=>$text){if($time<$unit) continue;$numberOfUnits = floor($time / $unit);return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');}
}
?>
JavaScript Relative Time Helpers
JavaScript makes relative times compatible with caching
Relative Time in JavaScript
well javascript implementation of what u have posted is available here also this may also be useful for you
Related
I want to reset a variable automatically without any user interaction to 0 every midnight.
How to do that in vanilla Javascript?
Or does Chrome have any default method to do it. Because I store that variable in Chrome.storage.local.
What is the best way to do it in either vanilla JS or using chrome apis?
It is impossible to do so automatically without user accessing the page.
But, you can add script to the page which onload check the last time the value was stored and if the time passed you can reset the variable.
Rough code to make this:
const isToday = (someDate) => {
const today = new Date()
return someDate.getDate() == today.getDate() &&
someDate.getMonth() == today.getMonth() &&
someDate.getFullYear() == today.getFullYear()
}
window.onload = function init() {
const { value, date } = JSON.parse(localStorage.getValue('key'));
if (!isToday(date)) {
localStorage.setValue('key', JSON.stringify({ date: new Date(), value: defaultValue}))
}
}
You've said you're storing the value in Chrome.storage.local. Also store the date/time you saved that value. When you load it, if midnight has passed since that time, reset the value to zero.
In case the page has been left open overnight, either always load the value from storage before using it (even if you already have it in a JavaScript variable), or do the same thing at the JavaScript level (remember the date/time and reset the value). Although you can set a timer, pages that sit idle for a long period of time have their timers de-prioritized by modern browsers, so it probably wouldn't be reliable to do this with a timer.
Without server assisting to do that, you may want to implement reset_variable() to be scheduled with helping of setTimeout() https://developer.mozilla.org/en-US/docs/Web/API/setTimeout and setInterval() https://developer.mozilla.org/en-US/docs/Web/API/setInterval - But you have to trigger setInterval() at midnight first, and adjust the interval as 24h. Thus, you have to implement some algorithm to calculate when to start executing (trigger) setInterval() using the setTimeout().
With server assisting, you may want to implement a cron-like job in the server. The job may look like sending some predefined values to reset the variable on the browser.
Therefore, you can do it in diverse ways. The simplest way is over WebSocket https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API.
Explanation:
Browser/Client-side:
Implement a Listener on the browser Ex, message event https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/message_event, whenever you caught a message, process that message if it's the predefined value to reset the variable, then someVar.reset().
Server-side:
Create a handler to connect to the client-side WebSocket Listener -WebSocket supported in most programming languages-.
Implement a cron-like job to execute a function every midnight. I have no idea if you have a server, and if so, which programming language you are using. However, a cron-like job can be implemented in several programming languages, and basically, it can be implemented natively on Unix-like OSs, you may want to ask another question if you need help regarding this.
The function should send a predefined value using the handler of the WebSocket connection.
-you can do some Security validation though-
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
Having a bad day. This one has stumped me all morning. All the solutions I've found have stopped one step short of where I need to go.
I have a legacy PHP/JS app that I'm working on. Rather than trying to explain it, I'll just show what I need to do.
<?php
$phpDate_1 = new Date($someDate);
$phpDate_2 = new Date($someOtherDate);
//...There are a bunch of these
$phpDate_n = new Date($endOfTime);
<script language="javascript">
function myFunction() {
var line = aUserSelection; //an int from user which tells me what date to use
//Next line is the problem. I'm trying to pull the month from the appropriate PHP date into the JS variable.
var theMonth = "<?php echo $phpDate_" + line + "->getMonth();?>";
}
</script>
?>
I must have tried 20-30 combinations of single and double quotes, escapes, dots, pluses, and so on, but I keep getting errors over the "line" part. Unexpected character, encapsed strings, etc.
Hoping someone can point me in the right direction because my brain is fried at this point. Answers in pure JS and PHP only please because that's how the app is built. Thanks.
You need to close your php (?>) before outputting the javascript to fix the syntax error that you got.
However, with that said, you are trying to incorporate the javascript line variable into the variable name for $phpDate, to generate something like $phpDate_1.
If you don't want to go with an AJAX solution, your best bet would be to output each line's date into a javascript array. This is strongly discouraged, but if this is a legacy application that you cannot make many changes to, this might be your only option.
I have 2 time inputs as 7:07:02 and 7:00
How can I find the difference between these two,I prefer to use jquery, Is there any jquery plugins available for this ? ( please let me know if you know other solutions for this )
Thanks a lot
I would recommend Date.js
(Date.parse('7:07:02') - Date.parse('7:00')) / 1000; // => 422 seconds
I don't think you want jquery. Just javascript will accomplish this. Change the two times to Dates and then add/subtract them as you like. Finally convert back to the date format that you want to use.
I'm developing a pet project with jQuery. Now the application requires some variable value is transferred to client javascript when the page is loaded. I'm wondering what's the best practice to do it.
I can image to do it in two ways. First, render it to be a javascript variable in the page.
<script> <?php echo "var maxid = $maxid;"?> </script>
Which means the client will see
<script> var maxid = <somevar>; </script>
Second, assign it to be an attribute of one element.
<div maxid="<php echo $maxid >" />
Which approach is better? Is there any other way to do it?
For the sake of valid html I'd go with the first method, though it really doesn't matter as long as it gets the job done.
<script>
$(function() {
var max_id = <?php echo $max_id;?>;
});
</script>
I use JSON string to pass values to client
Take a look at this example http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
I rarely have to pass just one variable ... I tend to have a whole set of information, in which case I use:
var myAwesomeStuff = <?php echo json_encode($myArrayOfAwesomeInformation); ?>
No round trip to the server, as mentioned earlier with JSON.
-- Edit:
Just so it's clear, your "question" is asking something totally different than your "code". You'll need to clarify, my post below talks about the "question".
-- Old:
I generally return the complete HTML to be rendered, in the pages that the ajax calls to.
The reason for this is that I don't have to duplicate layout logic in JavaScript, and it ends up being generally useful for just keeping the JavaScript trivial, and of the form of setting HTML/text content of relevant placeholders.
It comes at the cost of transferring more data, but for me, I'm happy to make this trade-off.
I would render it to be a javascript variable (your first alternative). This seems to be a common approach.
First method is better because you will consume less memory and CPU with a simple variable. Going the DIV way, you will consume a DOM element and a DOM node search to read the value.
I need to create a countdown clock, that counts down the days, hours, minutes and seconds that are left to a date of my choice, using jQuery or Google App Engine (Python).
I have created a timer using JavaScript but for that I was using the system time.
I need to use the server time. Can anybody give me ideas to build a count down timer using the server UTC time.
I created a timer using Javascript,But in that i used system time.
If that JavaScript really serves your needs, then that JavaScript code could easily be made dynamic as well. In the code, wherever the current system time is initialized, simply insert your server time using your language of choice (Python). In other words: use your server language (Python) to output the script just as it is right now, except for replacing the part that initializes the current time.
In PHP, some pseudocode (not sure about the arguments of the Date() constructor) might look like, for example:
// my_countdown_script.php
[..]
var startTime = new Date( <?php echo time(); ?> );
[..]
Then, rather than including your JavaScript, you would be including the PHP file that inserts the server time like above:
<script type="text/javascript" src="my_countdown_script.php"></script>
The good thing is: this will work in any browser that supports the JavaScript you already created.
(In some later version, your JavaScript could include some initializers that allow you to set the current time after including the library in your HTML. That would allow the actual JavaScript library to be static, and thus to be cached by the browser.)
a good jquery plugin can be found here http://keith-wood.name/countdown.html
all you need to do then is pass in your new date from your scripting language php/asp.net by setting a variable on the page before the initialisation and updating the _calculatePeriods function to take that variable instead of the now one.
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery.countdown.js"></script>
<script type="text/javascript">
$(function () {
var servernow = new Date( <?php echo time(); ?> );
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26);
$('#defaultCountdown').countdown({until: austDay});
$('#year').text(austDay.getFullYear());
});
</script>
from js/jquery.countdown.js
* Calculate the requested periods between now and the target time.
#param inst (object) the current settings for this instance
#param show (string[7]) flags indicating which periods are requested/required
#param now (Date) the current date and time
#return (number[7]) the current time periods (always positive)
by year, month, week, day, hour, minute, second */
_calculatePeriods: function(inst, show, now) {
// Find endpoints
inst._now = servernow;
Josh
You can reliably get server time from http://just-the-time.appspot.com/ -- an app engine app I made to help out a questioner on stack overflow, actually;-). Its simple code is opensourced at http://code.google.com/p/just-the-time/, and I could easily add the functionality you require (a page that, queried with the future date of your choice, returns days, hours, minutes and seconds to it, in some easily usable format) -- just let me know!
jQuery Timers is a plugin I've used in the past, and found to be very good.
Simply set two JavaScript variables to the current and target time for the countdown, and use a jQuery timer to update the "time remaining". If you want, you can add another time that re-synchronises the server and client times as well, every so often - though this probably isn't necessary.
why not simply use the UTC methods of the date object?
see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date
all local time methods have UTC counterparts
edit: this is meant to be used with his existing implementation in javascript.
If you really want to be sure you get the server time, do an XHR request (for anything) and check the Date header
So basically you need two things:
Page that displays the countdown time using the server time.
Client side updating of the time.
Render your time server side in something like this:
<span id="countdown" title="1245515631554">4 min. and 24 seconds</span>
Where the title is a timestamp of the current time that you can easily parse. You could also parse the text, but that requires more complex code.
Then add some Javascript that gets the time and updates the text every second. Setting a timeout that gets the date, updates it and sets the text.