using the time as a dynamic variable to compare values - javascript

I am working on programming a page in JS that grabs calendar data from an outside source, imports it into a multidimensional array and uses it to display who is currently working along with their photo, phone number, etc.
Right now I have it set up so that the page reloads every 15 minutes. I'd prefer to have this all done dynamically so that when, say, the clock strikes 5pm the page knows to update without having to wait until the 15 minute refresh is triggered.
All of the work times are pulled from the other calendar in 24 hour format (so 5pm is 1700).
Here's how I'm generating the current time to compare with the start/end times in the calendar:
//Get the current date and time
var dateTime = new Date();
var month = dateTime.getMonth() + 1;
var day = dateTime.getDate();
var dayOfWeek = dateTime.getDay();
var year = dateTime.getYear() + 1900;
//converting hours and minutes to strings to form the 24h time
var hours = dateTime.getHours().toString();
if (hours.length === 1) {
var hours = '0' + hours
};
var minutes = dateTime.getMinutes().toString();
if (minutes.length === 1) {
var minutes = '0' + minutes
};
var time = hours + minutes;
//convert the 24h time into a number to read from later
var timeNumber = parseInt(time);
I then use if statements to compare the start/end times from the imported schedule with timeNumber to determine who is currently working and push that to an array that is eventually displayed on the page with this code:
//figure out who is currently working and put them in the workingNow array
var workingNow = [];
for (i = 0; i < workingToday.length; i++){
//convert time strings to numbers to compare
var startTime = parseInt(workingToday[i][7]);
var endTime = parseInt(workingToday[i][8]);
//compare start and end times with the current time and add those who are working to the new list
if(startTime < timeNumber && timeNumber < endTime){
workingNow.push(workingToday[i]);
}
};
I guess I have just been trying to figure out how to make this comparison of the data in an array with the current time something that is dynamic. Is this possible or would I need to go about this in a completely different way from the ground up?

You should have a look at momentjs. This is a really good library to handle all sort of time and date manipulation.
http://momentjs.com/

Related

Getting the difference in milliseconds between two dates to be used in counter

I am using a counter library that will count down the amount of time allowed for user for reading a book section, that library will accept a milliseconds value to work.
Now i have function for getting the allowed time from api which contain the following code :-
// api request -> var data.created_at = contain the section read request created_at date/time.
var readAllowedurationInHr = 2;
var readAllowedDurationInDay = null;
var createdAt = new Date(data.created_at);
if (readAllowedDurationInDay) {
createdAt.setDate(createdAt.getDate() + readAllowedDurationInDay);
var diffInMilliseconds = createdAt.getTime() - Date.now();
}
if (readAllowedurationInHr) {
createdAt.setDate(createdAt.getHours() + readAllowedurationInHr);
var now = new Date();
var diffInMilliseconds = createdAt.getTime() - now.getTime();
}
setCounterValue(diffInMilliseconds);
The code for getting the days difference "if (readAllowedDurationInDay)" is working, but for handling the hour difference "if (readAllowedurationInHr)" it show in the counter a count down starting from 16 days.
How can i get the difference in hours between dates in millisecond unit ?

Momentjs / Angularjs - Checking if 2 dates are in the same period - TimeSheet project

I am working on a simple Timesheet app, I am trying to implement an auto calculator that will sum up your hours for each day (Sunday, Monday, Tuesday, etc ...). A problem I noticed is that in some cases, users will enter activities that will be within the same date time periods.
For example:
$scope.Example = [
{Description:"Example activity",Start:"2018-06-24 8:00",End:"2018-06-24 10:00",Total:2},
{Description:"Example activity2",Start:"2018-06-24 9:00",End:"2018-06-24 10:00",Total:1},
{Description:"Example activity3",Start:"2018-06-24 10:00",End:"2018-06-24 11:00",Total:1}];
$scope.Calculate_all_entries = function(){
$scope.Total.Sunday = 0;
if($scope.Example){
angular.forEach($scope.Example, function(element){
if(moment(element.Start).format("dddd") === "Sunday"){
$scope.Total.Sunday = $scope.Total.Sunday + element.Total;
}
})
}
}
In this case the total should be 3 hours and not 4 hours as we dont charge for work within the same hours. I'm need to implement a system that would check if the dates are within the same period and provide the appropriate total.
I found this in the documentation on momentjs that seemed to be close to what i need but only takes one value:
moment('2010-10-19 11:00').isBetween('2010-10-19 10:00', '2010-10-25 00:00'); // true
Would anyone know of any other methods to check wether or not the start and end time are in the same period as other entries in the same day?
Sure, you can use momentjs's unix() function to convert those date times to an integer which then can easily be used to check whether the timestamp is in between two other timestamps.
Here is an example:
var timeToCheck = moment('2010-10-19 11:00').unix();
var startTime = moment('2010-10-19 10:00').unix();
var endTime = moment('2010-10-25 00:00').unix();
console.log(timeToCheck >= startTime && timeToCheck <= endTime); // true

add time from cells programmatically

I have a a spreadsheet which I use to note how I spent my time on a project. In that spreadsheet I have a couple of columns, one of which is the time spent doing something and the other is the category of what that something is (for example meetings or accounting or calling customers). I am trying to write a script which I pass the name of the category and it then loops though all the rows to see if the category equals the category I passed it, and if so it adds the time to the counter. I am however having trouble adding the time together. What I have so far is this:
function getTimeInCat(cat){
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var time = new Date();
var counter = 0;
for(var i = 6; i < numRows; i++){
var carCell = "F" + i;
var cellName = "E" + i;
if(sheet.getRange(i, 6).getValue() == cat){
time += sheet.getRange(i, 5).getValue();
counter++;
}
}
return time;
}
Instead of what I want I get this in return:
Thu Jan 30 2014 18:29:22 GMT-0000 (GMT)Sat Dec 30 1899 00:50:39 GMT-0000 (GMT)Sat Dec 30 1899 00:05:39 GMT-0000 (GMT)
EDIT: It is giving the right amount of rows (The remnants of that test are still in the code)
Try var time = 0. Date() I think will transform your time to a date.
The values of those cells are actually Date objects. This is why you're getting a long string of timestamps when you add the values of the cells together. For whatever reason, Google decided that when you're entering a duration, it will actually be an offset of HH:mm:ss after 12/30/1899. Try changing the format of those times to a date (Format > Number > Date) and you'll see it changes to that date.
Luckily, with Date objects, you can use the getTime() function to get your total duration. getTime() gives you the number of milliseconds since 1/1/1970 so it will actually return very large negative numbers for those cells but that's easy enough to manage. You just need to create a Date object with 12/30/1899 as the date and subtract that from the value of the cell you want.
var base = new Date("12/30/1899").getTime(); // -2.2091436E12
var cell = sheet.getRange(row,col).getValue().getTime(); // some other large negative number
var delta = cell - base; // this should be your duration in milliseconds

Make a date/time value called from an API tick very second. (JavaScript)

I'm calling a date and time through an API, which looks like this:
<?php $xml = simplexml_load_file("https://api.eveonline.com/server/ServerStatus.xml.aspx/"); ?>
<div class="server-time">
<?php echo $xml->currentTime; ?>
</div>
This will show a date and time like this on the page:
2013-10-16 08:15:36
Now I want this clock to tick every second and the time and even date (in case it's just seconds before midnight when the user visits the site) values to change accordingly, just like you would expect a digital clock to work.
I know this is possible with JavaScript but since I am a total rookie at it I don't know how to do this - at all.
Help would be highly appriciated!
There are many javascript clocks out there, you don't even have to use an API to get the time and date!
function clock(id) {
//Create a new Date object.
oDate = new Date();
//Get year (4 digits)
var year = oDate.getFullYear();
//Get month (0 - 11) - NOTE this is using indexes, so 0 = January.
var month = oDate.getMonth();
//Get day (1 - 31) - not using indexes.
var day = oDate.getDate();
//Get hours
var hours = oDate.getHours();
//Get minutes
var minutes = oDate.getMinutes();
//Get seconds
var seconds = oDate.getSeconds();
//Maybe create a function that adds leading zero's here
var dateStr = '';
dateStr += year+' - '+month+' - '+day+' '+hours+':'+minutes+':'+seconds;
//Append dateStr to some element.
document.getElementById(id).innerHTML = dateStr;
//Repeat the function every 1000 miliseconds aka 1 second
setTimeout(function() {
clock(id);
}, 1000);
}
The usage would be
<div id="yourID">clock input will go here</div>
clock('yourID');
NOTE
This function has to be called after the DOM is loaded, otherwise this would result in error.
This can be achieved by placing the script tag with your JS at the bottom of the page (not using jQuery that is).
Otherwise if using jQuery, call the $(function() {}) (equivelant to $(document).ready(function() {});
The function is quite self-explanatory, but maybe you would want to read up on the functions to see exactly what they do.
a quick google search should do the trick.
Anyways hope this helps, good luck :)
I'm not sure if you want it to fetch the time from the api every second or, if you want it to just increase every second, starting from the given api time. In the latter case, you should use setInterval:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = $('.server-time').text();
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
$('.server-time').text(date.toString());
}
setInterval(updateTime, 1000);
If you are not using jquery, just use document.getElementById or something like that:
change your element to:
<div id="server-time">
and use the following snippet:
function updateTime() {
// assuming you are using jquery for DOM manipulation:
var timestamp = document.getElementById('server-time').innerHTML;
var date = new Date(timestamp);
date.setSeconds(date.getSeconds() + 1);
document.getElementById('server-time').innerHTML = date.toString();
}

calculate age javascript in adobe acrobat

I am having some difficulties getting a field to populate in an interactive PDF form. I am using a javascript to calculate the current age of client from 2 date fields (DateToday and ClientDOB) already in the form and I need it to populate a "ClientAge" field. The DateToday field automatically populates when the form is opened. I would like for the ClientAge field to populate after the user selects the ClientDOB.
This is what I am trying to have it do. Should be simple I would think.
DateToday - ClientDOB = ClientAge
Here is my code:
var DateToday_ = Date2Num(DateToday.formattedValue, "MM/DD/YYYY")
var ClientDOB_ = Date2Num(ClientDOB.formattedValue, "MM/DD/YYYY")
var diff = DateToday_ - ClientDOB_
ClientAge.value = Floor(diff / 365.25)
I am not sure why the ClientAge field will not populate once the ClientDOB has been selected. Any replies would be helpful. Thanks.
This was taken from somewhere off the 'net. Can' remember where. However I have used this in a number of forms and it works fine. The idea is that the difference between dates is in milliseconds, and a given date is the number of seconds from a fixed date in the past. Once you have the difference in seconds between the dates (in this case DOB to the present) you can calculate how many years that is. Note that my format is in British date format (dd/mm/yy). If you operate in American format (mm/dd/yy) you must make the appropriate changes.
// get current date THIS NON AMERCAN DATE FORMAT
var oNow = new Date();
// get date from 'Demo.DOB' field
var oMyDate = util.scand('dd/mm/yy', this.getField('Demo.DOB').value);
// define second in milliseconds
var nSec = 1000;
// define minute in milliseconds
var nMin = 60 * nSec;
// define hour in milliseconds
var nHr = 60 * nMin;
// define day in milliseconds
var nDay = 24 * nHr;
// compute today as number of days from epoch date
var nNowDays = Number(oNow) / nDay;
// truncate to whole days
nNowDays = Math.floor(nNowDays);
// compute inputted date days from epoch data
var nMyDateDays = Number(oMyDate) / nDay;
// truncate to whole days
nMyDateDays = Math.floor(nMyDateDays);
// compute difference in the number of days
var nDiffDays = nNowDays - nMyDateDays;
// adjust difference for counting starting day as 1
++nDiffDays;
// convert days to years
var nYears = nDiffDays / 365.2525
// truncate to whole years
nYears = Math.floor(nYears);
// set field value number of years (nYears)
event.value = nYears;

Categories

Resources