SP2013 get time difference in minutes - javascript

I have a list with a date-time column called "Status Date". What I need to do is display the number of hours and minutes between "Status Date" and Now() in a calculated column.
The CONCATENATE method does not work, because it only updates when the list item is edited. I need the time difference to update each time the page loads. I am using the workaround to leverage javascript in an tag. However, when I try to use the "Status Date" field in a new Date() method it returns as "Wed Dec 31 19:00:43 EST 1969"
here is my code for the calculated column. It returns the number of minutes in the current hour.
<img src='/_layouts/images/blank.gif' onload=""{var startTime=new Date("&[Status Date]&");var endTime=new Date();var difference=endTime.getTime()-startTime.getTime();var rawMins=1000*Math.round(difference/1000);mins= new Date(rawMins);this.parentNode.innerHTML= 'Minutes: '+ mins.getUTCMinutes() ;}"">

Use JSLink for this requirement.
Similar thread here
<script type="text/javascript">
(function () {
'use strict';
var CustomReminder = {};
/**
* Initialization
*/
function init() {
CustomReminder.Templates = {};
CustomReminder.Templates.Fields = {
'Reminder': {
'View': customDTDisplay
}
};
// Register the custom template
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(CustomReminder);
}
function customDTDisplay(ctx) {
//from the context get the current item and it's value
if (ctx != null && ctx.CurrentItem != null) {
//your render logic
}
}
// Run our intiialization
init();
})();
</script>

Related

Redirect after countdown ends

Currently, I have this in my HTML code and am not 100% sure on how to redirect to another page I have after the countdown finishes. I am not too familiar with javascript at the moment either, any help is appreciated. I know that when the page loads it takes the current time ( at the .now snippet) and just adds 10 seconds to it rather than a set time the script should end at then display the difference between present and that set time. The issue with this is that when anyone loads this page it would always show a countdown for 10 seconds to it rather than a universal countdown. For example, the time currently is 3:53 and should end at 4:00. Once the time hits 4 push the redirect.
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10
});
});
</script>
You want to get the time from a fixed one. So, utilize Date built-in API instead of jQuery's $.now(), because
This API has been deprecated in jQuery 3.3; please use the native Date.now() method instead.
What time do you want? Determine it beforehand (GMT):
const date1 = new Date('September 13, 2021 04:00:00');
Then, when subtracting the dates you'll get the time remaining.
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: date1 - new Date() // gets the difference between determined date and current date
onEndCallback: () => {
window.location.href = "http://www.example.com";
}
});
});
</script>
Remember to handle the case when the time of access was after the pre-defined time.
add a callback parameter (function) to your countdown
<!--Countdown Script -->
<script type="text/javascript">
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10,
onEndCallback: function () {
window.location.href = "http://www.newlink.com";
}
});
</script>
If you're trying to redirect and doesn't matter if is using javascript or not, use the tag from the HTML.
<meta http-equiv="refresh" content="10; URL="https://www.mywebsite.com.br/" />
It will count to 10 and redirect to your URL
I'm assuming this is the ClassyCountdown() jQuery plugin you are using: https://github.com/arsensokolov/jquery.classycountdown
If that's the case, it has an onEndCallback which is called once the countdown reaches 0.
So your code would become something like this:
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10,
onEndCallback: function () {
document.location.href = 'https://www.google.com' // <- The url to redirect to
}
});
});
</script>
Updated answer to redirect at an absolute time:
$(document).ready(function() {
setInterval(function() {
// This is when you want the redirect to happen
// This is the absolute time, as reported by the users browser
let hour = 21;
let minute = 18;
let second = 20;
let date = new Date();
if (date.getHours() == hour && date.getMinutes() == minute && date.getSeconds() >= second) {
document.location.href = 'https://www.whatever.com';
}
}, 1000);
});

Updating Full Calendar Day At Midnight

//Reset At Midnight
function resetAtMidnight() {
var now = new Date();
var night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1, // the next day, ...
0, 0, 0 // ...at 00:00:00 hours
);
var msToMidnight = night.getTime() - now.getTime();
setTimeout(function() {
reset(); // <-- This is the function being called at midnight.
resetAtMidnight(); // Then, reset again next midnight.
}, msToMidnight);
}
function reset() {
$('#calendar').fullCalendar('today');
}
I am trying to have FullCalendar.js update the current day everyday at midnight. I pulled this reset snippet from another post on here - but the reset function does not seem to execute.
You have not provided full detail so I don't know what exactly you need but following code might help you to solve your issue.
You can check midnight quite easily using moment.js library.
Following code was taken from another post Best Way to detect midnight and reset data
$(document).ready(function() {
var midnight = "0:00:00";
var now = null;
setInterval(function() {
now = moment().format("H:mm:ss");
if (now === midnight) {
alert('reset() function here');
}
$("#time").text(now);
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<code id="time"></code>
Fullcontrol:
You can either use rerenderEvents or refetchEvents as per your requirement. So it will be something like this
function reset(){
$('#calendar').fullCalendar('rerenderEvents');
OR
$('#calendar').fullCalendar('refetchEvents');
}
If you want to re-draw the fullcontrol then here is another informative post 're-draw fullcalendar'
As post suggested you can do
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar('render');

Check is class exist longer than X in javascript

I wrote simple monitor which check few things on my networks and display status - I am fetching statuses using ajax.
When something is wrong I am adding class error to div which is displaying current status.
Later I add player with error sound when class error is present it plays music. I set 3 second interval and thats all.
But not always error mean error, sometimes I recive false warning.
Now I am looking for way to play sound when class error exists longer than XX seconds.
I suppose I have to wrote function with interval 1s, add every hit 1 to temp variable and check is variable bigger than else clean temp variable, but maybe is there more elegant way.
i guess it should work
$('.error').each(function(){
var e = $(this)
setTimeout(function(){
if (e.attr('class') == 'error'){
e.attr('class','error-with-sound');
}
},2000);
});
You should take two vars store the current time at their respective events.
var oldTime, newTime;
// Now when you are adding the class
$(something).addClass("someclass");
oldTime = new Date().getTime(); // Store the timestamp.
//And when you are removing the class
$(something).removeClass("someclass");
newTime = new Date().getTime(); // Store the timestamp.
// Now you check whether class was added for more then XX Seconds
var _diff = (newTime - oldTime)/1000; // Diference is in seconds.
There is no direct way for that, you can add timestamps in your class with separator something like error_1448953716457 and later you can split that and can compare with current timestamps
$('#na').click(function () {
var t = new Date().getTime();
$('h1').addClass("error_" + t);
});
$('#nr').click(function () {
var t = new Date().getTime();
$("[class^=error]").each(function (e) {
$("span").html("Diff. Seconds : " + ((t - ($(this).attr('class').split(' ').pop().split('_')[1])) / 1000).toString());
});
});
input {
width:100px;
}
.error {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>.addClass()</h1>
<input id="na" value="Add Class1" type="button" />
<br/>
<input id="nr" value="Calculate Diff" type="button" />
<span></span>
If you want to track .error elements on the page, set an independent interval that looks for those elements and tracks the ones it has seen before by setting an attribute or data value in jquery.
Remember to clearInterval(interval) if you no longer need to check for .error elements.
(function ($) {
// set constants in milliseconds as desired
var INTERVAL_LENGTH = 100, // how often to check DOM for error elements
NOTIFY_AFTER = 3000; // handle error after this length
// check for .error elements and handle those that have been around for a while
var interval = setInterval(function () {
var now = Date.now();
$(".error").each(function () {
var t = $(this).data('error-time');
if(t) {
if(now - t > NOTIFY_AFTER) {
handleErrorElement(this);
}
}
else {
$(this).data('error-time', now);
}
});
}, INTERVAL_LENGTH);
function handleErrorElement(elem) {
// do what you need for error elements visible past a threshold
console.log("handling error element: ", elem);
}
})(jQuery);

How can I make my two JavaScripts work together?

Hello I am trying to have my clock and my countdown timer on the same page so people/users can see when I am done with my game and for them to have the correct time with the countdown timer also. Here is the code. They both work separately but when the are both put on a .php page only the bottom one (countdown timer) works and if I do JQuery.noconflict to the timer the clock works but the countdown doesn't.
<!-- Clock Part 1 - Holder for Display of Clock -->
<span id="tP"> </span>
<!-- Clock Part 1 - Ends Here -->
<!-- Clock Part 2 - Put Anywhere AFTER Part 1 -->
<script type="text/javascript">
// Clock Script Generated By Maxx Blade's Clock v2.0d
// http://www.maxxblade.co.uk/clock
function tS(){ x=new Date(); x.setTime(x.getTime()); return x; }
function lZ(x){ return (x>9)?x:'0'+x; }
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; }
function dE(x){ if(x==1||x==21||x==31){ return 'st'; } if(x==2||x==22){ return 'nd'; } if(x==3||x==23){ return 'rd'; } return 'th'; }
function y2(x){ x=(x<500)?x+1900:x; return String(x).substring(2,4) }
function dT(){ window.status=''+eval(oT)+''; document.title=''+eval(oT)+''; document.getElementById('tP').innerHTML=eval(oT); setTimeout('dT()',1000); }
function aP(x){ return (x>11)?'pm':'am'; }
var dN=new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'),mN=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),oT="dN[tS().getDay()]+' '+tS().getDate()+dE(tS().getDate())+' '+mN[tS().getMonth()]+' '+y2(tS().getYear())+' '+':'+':'+' '+tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+aP(tS().getHours())";
if(!document.all){ window.onload=dT; }else{ dT(); }
</script>
<!-- Clock Part 2 - Ends Here -->
<script type="text/javascript">
//###################################################################
// Author: ricocheting.com
// Version: v3.0
// Date: 2014-09-05
// Description: displays the amount of time until the "dateFuture" entered below.
var CDown = function() {
this.state=0;// if initialized
this.counts=[];// array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval=null;// setInterval object
}
CDown.prototype = {
init: function(){
this.state=1;
var self=this;
this.interval=window.setInterval(function(){self.tick();}, 1000);
},
add: function(date,id){
this.counts.push({d:date,id:id});
this.tick();
if(this.state==0) this.init();
},
expire: function(idxs){
for(var x in idxs) {
this.display(this.counts[idxs[x]], "Sorry, hopfully we are open in a couple minutes");
this.counts.splice(idxs[x], 1);
}
},
format: function(r){
var out="";
if(r.d != 0){out += r.d +" "+((r.d==1)?"Day":"Days")+", ";}
if(r.h != 0){out += r.h +" "+((r.h==1)?"Hour":"Hours")+", ";}
out += r.m +" "+((r.m==1)?"Min":"Mins")+", ";
out += r.s +" "+((r.s==1)?"Sec":"Secs")+", ";
return out.substr(0,out.length-2);
},
math: function(work){
var y=w=d=h=m=s=ms=0;
ms=(""+((work%1000)+1000)).substr(1,3);
work=Math.floor(work/1000);//kill the "milliseconds" so just secs
y=Math.floor(work/31536000);//years (no leapyear support)
w=Math.floor(work/604800);//weeks
d=Math.floor(work/86400);//days
work=work%86400;
h=Math.floor(work/3600);//hours
work=work%3600;
m=Math.floor(work/60);//minutes
work=work%60;
s=Math.floor(work);//seconds
return {y:y,w:w,d:d,h:h,m:m,s:s,ms:ms};
},
tick: function(){
var now=(new Date()).getTime(),
expired=[],cnt=0,amount=0;
if(this.counts)
for(var idx=0,n=this.counts.length; idx<n; ++idx){
cnt=this.counts[idx];
amount=cnt.d.getTime()-now;//calc milliseconds between dates
// if time is already past
if(amount<0){
expired.push(idx);
}
// date is still good
else{
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if(expired.length>0) this.expire(expired);
// if no active counts, stop updating
if(this.counts.length==0) window.clearTimeout(this.interval);
},
display: function(cnt,msg){
document.getElementById(cnt.id).innerHTML=msg;
}
};
window.onload=function(){
var cdown = new CDown();
//Year,Month,Day,Hour,Min,Sec\\ (Jan - 0 Fed - 1 ++ Dec - 11, 12 is replaced with 0 for Jan)
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
};
</script>
<h2> Time until ^^<<>> opens!</h2>
<div id="countbox1"></div>
Fixed the problem
Thanks to #Scronide , #James Thorpe , and #Ultimater. I put all of your methods into place and kept them separate and used #Scronide final method. Thanks again.
They're both assigning to window.onload so the second is overwriting the function of the first.
If you are using jquery, instead of assigning to window.onload, you can instead use:
/* first component */
//initialisation for first component
$(function() {
dT();
});
/* second component */
//initialisation for second component
$(function() {
var cdown = new CDown();
//Year,Month,Day,Hour,Min,Sec\\ (Jan - 0 Fed - 1 ++ Dec - 11, 12 is replaced with 0 for Jan)
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
});
Both use window.onload. Simply join the two functions into one.
Neither of these scripts use any jQuery, so it isn't a jQuery conflict. The problem is that they are both setting a function to window.onload, so the last script will always override the one before it.
I suggest removing the if(!document.all){ window.onload=dT; }else{ dT(); } line from the end of the clock script and adding dT(); inside the window.onload assignment from the second script.
So you would have something like:
window.onload=function(){
dT();
var cdown = new CDown();
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
};

Display html content between defined hours mon to friday

i was wondering if there is a quite simple solution to display content between certain hours and only during working days in a Europe timezone?
The hours will be everyday (except weekends) between 9AM and 5PM, between those times a html content should be shown.
If possible a different html content from 5PM till 9AM.
The short version is that you use new Date() to get the current date/time, and then you use DOM manipulation to add/remove that content as appropriate. If you want content to change in-between page loads, you'll probably also want a window.setInterval running to update things constantly.
You might want to check out the Moment.js library (http://momentjs.com/), as it has a number of functions which make working with dates/times easier.
Here's a quickie example (without using Moment) that just checks "are we past 5 or not?":
window.setInterval(function() {
if (new Date().getHours() > 17) { // if it's after 5pm (17:00 military time)
$('#someContent').hide();
} else {
$('#someContent').show();
}
}, 1000 * 60) // this will run every minute
With that hopefully you can figure out how to add the other needed if checks.
Here you go! :)
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
answered Nov 30 '10 at 22:16
rhino

Categories