Livestamp Plugin Jquery - how to show a time? - javascript

I use this jquery plugin: livestamp.
If you know, tell please, how to show time (hours, minutes ago) only for the current day. After 24 hours on next day - to show label "yesterday" or simple date.
Thank you!

By default, I don't think livestamp can do this.
But, at the bottom of livestamp's examples, they have some code to animate the text when it changes by hooking into the change.livestamp event.
We can use moment.js to modify this code to do what you're asking.
$('#animation').on('change.livestamp', function(event, from, to) {
event.preventDefault(); // Stop the text from changing automatically
// Get the original timestamp out of the event
var originalTS = event.timeStamp;
// Make a new moment object to compare the timestamp to
var newDate = moment();
// Use moment's .diff method to get the ms difference between timestamps
var delta = newDate.diff(originalTS);
// If the difference is less than a day's worth of ms
if (delta < 86400000){
// Use formatted text provided by the change event
$(this).html(to);
}
else {
// Format the moment object with whatever moment format you want
$(this).html( newDate.format("dddd M/D/YYYY") );
}
}).livestamp();
I haven't used livestamp, but it seems to rely on moment existing for its formatting options, so this should just work.
Livestamp's source is super small, so consider hacking on it yourself if you have other stuff you want to be able to do.

Related

Decrement a variable once a day - Javascript

I'm trying to decrement a variable once a day. I have written the following code for that.
var counter = 10; //any value
setInterval(function() {
counter = counter - 1;
}, 86400000);
Is there a better or efficient way to achieve the same thing ?
P.S : - I do not wish to use any libraries.
The only thing I see you miss is to set the initial value of counter variable.
I would write:
var counter = 1000; // or any useful value
setInterval(function() {
--counter;
}, 24 * 60 * 60 * 1000); // this is more self-explanatory than 86400000, and, being evaluated just once, it will have a tiny effect on the performace of the script
I don't see any problem in the way you write it. You use interval, ok, but this is not the worst evil you may do to set up the variable value.
You may think of another solution with a function which returns you the current counter.
var initialValue = 20000;
function getCounter() {
return initialValue - Math.floor(Date.now() / 1000 / 60 / 60 / 24);
}
console.log(getCounter());
The difference is that it takes the current day number starting from the UNIX time beginning. Every day the day number will be increased, so the result of the function will be decreased by 1.
But still I don't see how this solution can be better than yours.
I'm not totally sure why, but using setInterval like this makes me uncomfortable.
If I were to require this, I would use something like this approach:
var counter = 10;
var timeout = new Date();
setInterval(function(){
if(new Date() >= timeout)
{
--counter; // the action to perform
timeout = new Date(timeout.getTime() + 86400000); // update the timeout to the next time you want the action performed
}
console.log(counter);
},1000); // every second is probably way more frequent than necessary for this scenario but I think is a decent default in general
One thing that this allows is to, for example, set the next timeout to midnight of tomorrow rather than being locked in to "X seconds since the previous execution". The key is the inversion of control - the action itself can now dictate when it should next run.
Though I would probably abstract away the details behind an interface accepting a start, interval, and action.
The biggest problem in my eyes is that you have to keep this one JS process running consistently for days at a time to have it do what you need. The world is not so perfect that things don't need an occasional reboot...including the average JS process.
Personally I would store a timestamp of my starting point, then (whenever I need to know how much time has elapsed) grab a new timestamp and use it to calculate how many days it has been. That way even if something interrupts my process I can still be right where I started.
Maybe use window.localStorage to save the last time, and if it is greater than 60*60*24 (seconds in a day) set the last time to this morning/now/1:00 and then decrease the value and save it.
Example:
var d = new Date();
var mins = -(1+d.getHours())*60+d.getMinutes();
var secs = mins*60+d.getSeconds(); // total seconds passed today from 1:00
var now = d.getCurrentTime():
var lastCheck = localStorage.getItem("lastCheck");
if (!lastCheck)
{
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
var dayPassed = now - lastCheck > 24*60*60; // change to see if a day has passed
if (dayPassed)
{
// save seconds
localStorage.setItem("counter",localStorage.getItem("counter")-1);
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
It makes more sense to me to check how many days have passed since a specific date and decrement that number of days from the counter. Mostly just because I wouldn't expect anybody to leave the same page open without the need or want to reload for days on end. I would do something like this:
counter = 365; // original counter
var start = new Date(2016, 03, 20); // original date
var now = new Date();
var days = Math.floor(Math.abs(start.getTime()-now.getTime())/(24*60*60*1000))
counter -= days;
That way every time you visited the page, it would be decremented correctly. Note that this ignores any issues with leap days or time zones. The example above would have a counter of 360 for me. And then if you did expect it to be open for days, reload it automatically with:
self.setTimeout(function(){document.location.reload()}, 86400000);

oldValue for dates in Google Apps Script

I am using an onEdit trigger to trigger a Google Apps Script. Essentially, I am using the results of a Form to populate a calendar event. Once I've created the calendar event, I want to be able to keep it in sync with the form entry. So if someone edits the form data, I want to edit the calendar event. Unfortunately, since there is no getEventById storing the eventId is not enough.
I was thinking I might be able to use the event['oldValue'] which stores the event time to figure out when the event used to be (in case it changes) to get a list of events at that time which will allow me to iterate through a small number of events to find the calendar event.
Unfortunately, the date object comes out as a weird floating point number that I can't parse. e.g: 1/19/2016 20:00:00 comes out as 42388.791666666664 which I really don't understand.
I did have another thought, should I just use a regular HTTP get call to get the event I want? I'm not exactly sure how to do that from within a Google Apps Script
Maybe late, but you can see the answer here
var x = 42521.015713761575;
// seconds in day = 24 * 60 * 60 = 86400
var date = new Date(1899, 11, 30, 0, 0, x * 86400);

How's a "duration picker" called and does it exist?

I'm looking for something like a "duration picker". Because googling "duration picker" doesn't give me any result, I would like to know if there is a technical name for it which can help in searching it. Time picker and Time Span picker doesn't bring anything helpful at the moment.
If something similar exists and someone can point me to that, it's ok instead of the technical name.
Update 1:
Sorry I completely forgot to explain what I mean by duration picker.
It's not a time picker, but a way to choose how much time will last doing something, not relative to a date. For example, cooking a given recipe will take (duration) 4 hours and 10 minutes. Traveling from here to there will take 4 days and 10 hours.
My basic idea is the possibility to configure the picker for the "bigger" unit to use (days probably), the duration will be expressed in seconds internally. So I can say 20 days and 23 hours and 0 minutes or if the "bigger" unit is days (for a software development job for example), I can write 150 hours and 30 minutes and 0 seconds.
It would be nice the option to hide some smaller fields, like minutes/seconds.
Update 2:
A very simple ui example:
You could use a set of customized jQuery spinners
$('#seconds').spinner({
spin: function (event, ui) {
if (ui.value >= 60) {
$(this).spinner('value', ui.value - 60);
$('#minutes').spinner('stepUp');
return false;
} else if (ui.value < 0) {
$(this).spinner('value', ui.value + 60);
$('#minutes').spinner('stepDown');
return false;
}
}
});
like this:
http://jsfiddle.net/xHzMw/1/
I know this question is old, but it seems like a satisfactory answer wasn't reached. I made a jQuery plugin for this exact use case, i'll post it for anyone that comes looking in the future like I did.
https://github.com/Tartarus762/jquery-duration-picker
Bootstrap Duration picker - Github, npm.
Dependencies: jQuery and Bootstrap 3 (for styling only).
Its called just like you called it and exists at http://shop.ekerner.com/index.php/shop/javascript/duration-picker-detail
I think you're looking for something like this jQuery plugin: http://www.jqueryscript.net/time-clock/Lightweight-Duration-Picker-Plugin-For-jQuery-Semantic-UI.html

JavaScript: Multi Time Zones Clocks

I want to display 3 clocks from 3 different time zones using JavaScript.
I browsed around the web searching for a simple solution but all I found was long scripts and .js extensions, all those to complete a simple task.
Is there an easy way to do this? do I really have to add an additional JS file to complete this task?
Thanks in advance to the helpers!
Is there an easy way to do this?
Yes.
do I really have to add an additional JS file to complete this task?
No. However, time handling in JS is difficult, since it has no really cross-browser-safe date/timestring parsing and formatting methods. It can be helpful to use a library for that, however that won't be necessary for your clock.
// all three clocks represent current time
var clock1 = new Date(); // current moment
var clock2 = new Date();
var clock3 = new Date();
// for outputting, adjust them
// leave clock1 in UTC
clock2.setHours(clock2.getHours() + 3); // UTC+3
clock3.setHours(clock3.getHours() - 5); // UTC-5
// now for display, use these values:
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();

Run code once a day

I was just wondering if it is possible to have a javascript for loop that only iterates through the loop once a day i.e. when the date changes?
for(i=0; i < myArray.length; i++){
alert(myArray[i]);
}
So in the above loop, let it run, and freeze it or something only till the data changes, and the do another iteration, and just keep on doing that.. You know what I mean.
Thanks in advance!
Using localStorage is the best way to go when you don't have a server (because a user can change the computer's time and break your logic, and using a server it's harder to hack this)
Method below is more bulletproof:
// checks if one day has passed.
function hasOneDayPassed()
// get today's date. eg: "7/37/2007"
var date = new Date().toLocaleDateString();
// if there's a date in localstorage and it's equal to the above:
// inferring a day has yet to pass since both dates are equal.
if( localStorage.yourapp_date == date )
return false;
// this portion of logic occurs when a day has passed
localStorage.yourapp_date = date;
return true;
}
// some function which should run once a day
function runOncePerDay(){
if( !hasOneDayPassed() ) return false;
// your code below
alert('Good morning!');
}
runOncePerDay(); // run the code
runOncePerDay(); // does not run the code
If you want something to happen at predefined intervals, you can set a timeout/interval:
http://www.w3schools.com/js/js_timing.asp
For example:
var dayInMilliseconds = 1000 * 60 * 60 * 24;
setInterval(function() { alert("foo"); },dayInMilliseconds );
edit: since you mentioned that the code will be running in a browser, this assumes the browser is running for at least 24 hrs and will not work otherwise.
the best way to achieve it is by creating a cookie that lasts for1 day..
Even if after the refresh of the web page or browser gets closed that countdown will still continue..
setcookie($cookie_name, $cookie_value, time() + 86400, "/");
This means 86400 = 1 day
Hope it helps

Categories