I'm working in Acrobat Pro 9 (using JavaScript), and I'm trying to these form fields to work correctly. The user needs to enter a duration of time (MM:ss) in several fields, and then have the total duration sum up at the bottom, also displaying as MM:ss.
I had used this code to create the total Time
//Get the total from hidden field
var v1 = getField("Total minutes").value;
// Define a constant to be used below:
var numSecondsInMinute = 60;
// The total number of seconds:
var numSeconds = v1*60;
// Extract the number of minutes from the total number of seconds - rounded down:
var numMinutes = Math.floor(numSeconds / numSecondsInMinute);
// Subtract the extracted number of minutes (converted to seconds) from the total number of
// seconds to get the remaining number of seconds:
numSeconds -= (numMinutes * numSecondsInMinute);
// Build a string from the final number of minutes and number of seconds in (MM:SS) format:
var finalTime = "(" + numMinutes + ":" + numSeconds + ")";
// Display the final time:
event.value=finalTime;
But that doesn't help with getting a total our of various MM:ss fields (e.g. 1:30 for a minute and a half, or 2:15, or 7:00).
Any ideas?
You can use the Acrobat JavaScript util.scand() method to convert the strings entered into the various MM:ss fields into JavaScript Date objects, perform the math, then convert the result back to a string using the util.printd() method, then set that value as the "Total Minutes" value.
Related
I'm currently using https://date-fns.org/v2.21.1/docs/differenceInSeconds to format distance between 2 dates in seconds, but if such distance is greater than 1min, various results come up like 67 seconds.
To make it more user friendly, I'd like to format this distance as mm:ss so
00:59
01:00
02:34
And so on. Currently closest I got to is using differenceInSeconds and differenceInMinutes and just concatenating 2 into a string like ${differenceInMinutes}:${differenceInSeconds} issue is, that for 2 minutes I get result like 02:120
You need to use the modulo (%) operator, it returns the remainder of division.
I've also used the padStart function to have the leading zeros displayed in the final string.
As the argument you just need to use the difference in seconds,
Here's a code snippet:
function formatTime(time) {
// Remainder of division by 60
var seconds = time % 60;
// Divide by 60 and floor the result (get the nearest lower integer)
var minutes = Math.floor(time / 60);
// Put it all in one string
return ("" + minutes).padStart(2, "0") + ":" + ("" + seconds).padStart(2, "0");
}
console.log(formatTime(15))
console.log(formatTime(65))
console.log(formatTime(123))
I'm trying to edit following code to get the output I want.
function zoo_countdown_end_day() {
if ($('.zoo-get-order-notice .end-of-day')[0]) {
var offset = $('.end-of-day').data('timezone');
var day = new Date();
var utc = day.getTime() + (day.getTimezoneOffset() * 60000);
let d = new Date(utc + (3600000*offset)),
duration = 60 * (60 - d.getMinutes());
let timer = duration, minutes;
let hours = (23 - d.getHours());//kumudu edited this
hours = hours < 10 ? '0' + hours : hours;
let label_h = $('.zoo-get-order-notice .end-of-day').data('hours');
let label_m = $('.zoo-get-order-notice .end-of-day').data('minutes');
setInterval(function () {
minutes = parseInt(timer / 60, 10);
minutes = minutes < 10 ? "1" + minutes : minutes;
$('.zoo-get-order-notice .end-of-day').text(hours + ' ' + label_h + ' ' + minutes + ' ' + label_m);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
}
zoo_countdown_end_day();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
This is the current output:
I just want to edit countdown time to countdown from next day 4.00 P.M (hours and minuets). Because I offer next day shipping.
Ok, the long and short of this answer is that it uses 2 functions to help..
countDown: this function takes in a functionwhileCountingDown, a numberforHowLong, then another functionwhenFinishedThen
whileCountingDown being triggered EACH second with the parameter being the amount of time left in seconds
forHowLong is the amount of seconds this countdown will last
whenFinishedThen is a function that activates AFTER the countdown is over.. it can be anything(like making a new countdown as well)
timeParse: this function takes in a numberseconds and then returns a string that looks like a more human version of time
eg: timeParse(108010), 108010 is 30 hours and 10 seconds, and it would return "1 day, 6 hours, 0 minutes"
The combination of these functions are able to have a countdown system working very well.. I ALSO DO NOT KNOW WHERE YOU GET YOUR FUTURE TIME FROM,
but if you get it in a timestamp format(like 1611860671302, a value that I copied from new Date().getTime() as I was typing this),
the line where you see 30*3600, replace that line with ((dateStamp-new Date().getTime())/1000).toFixed(0)
//honestly I don't even see where it's counting down from so i just made a countdown function that works in seconds and scheduled 30 hours from now(from when you run code).. just the format would probably need changing(since i don't know what format you want)
function zoo_countdown_end_day() {
var elem=$('.zoo-get-order-notice .end-of-day')[0]
//like I said, I didn't even see where you're taking the future time from but I'll just give a future time the equivalent of +30 hours
countDown(
(t)=>elem.innerText=timeParse(t), //every second, remaining time shows in specified element
30*3600, //seconds equivalent for 30 hours.. if you have a future dateStamp, before the countdown function, let dateStamp=this datestamp you would have, THEN change this line to.. ((dateStamp-new Date().getTime())/1000).toFixed(0)
()=>console.log("Timer Complete")
)
}
zoo_countdown_end_day();
//...............................................................
//time parsing function(takes in seconds and returns a string of a formatted date[this is what can change to change the look])
function timeParse(seconds){
var words=[
(num)=>{if(num==1){return("second")}return("seconds")},//this would return a word for seconds
(num)=>{if(num==1){return("minute")}return("minutes")},//this would return a word for minutes
(num)=>{if(num==1){return("hour")}return("hours")},//this would return a word for hours
(num)=>{if(num==1){return("day")}return("days")}//this would return a word for days
]
var timeArr=[seconds]
if(timeArr[0]>=60){//if seconds >= 1 minute
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=60){//if minutes >= 1 hour
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=24){//if hours >= 1 day
timeArr.unshift(Math.floor(timeArr[0]/24))
timeArr[1]=timeArr[1]%24
}
}
}
timeArr=timeArr.reverse()
.map((a,i)=>`${a} ${words[i](a)}`)
.reverse() //puts words to values and then reverses it back to correct order
timeArr.splice(timeArr.length-1,1) //takes out seconds part from being returned leaving days, minutes and hours
return(timeArr.join(', ')) //a mixture/combination of the forEach formatting(joining numbers with words), what is returned from words array and how they're joined contributes to the formatted look
}
//...............................................................
//countDown function(that works in seconds)
function countDown(whileCountingDown, forHowLong, whenFinishedThen){
//basic run down is, whileCountingDown is a function, forHowLong is a number, whenFinishedThen is a function
//in depth run down is:
/*
whileCountingDown(with parameter of how much time left in seconds) is activated every second until forHowLong seconds has passed, then whenFinishedThen is triggered
*/
var i=setInterval(()=>{forHowLong--
if(forHowLong<=0){//count finished, determine what happens next
clearInterval(i); whenFinishedThen()
}
else{whileCountingDown(forHowLong)}//do this for each second of countdown
},1000)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
I want to create a time differance calculator between two given time and a date number.
Also I want to tell you that I have made 4 input fields: time1, time2, days and timediff.
The time format that I want is very simple, ex: 700 for 7:00, 932 for 9:32, 1650 for 16:50 and so on...
Now I also have the day input field, where I can put in some numbers, ex: 1(for the first day, 2 for the second day and so on).
I want that if I put 1(first day) to not calculate the days, only to calculate the timediff, because it's the same day. But if I put 2 on the date field then 24hours(one day) to be added to the timediff, if I put 3 48hours(two days) to be added and so on...
I have something like this, but is not working well, when I change the day the result is mess up...
var time1 = document.getElementById('indulas').value;
var time2 = document.getElementById('erkezes').value;
var day = document.getElementById('nap').value;
if (day > "1"){ day * 2400 };
var time = (time2 * day) - time1;
document.getElementById('ido').value = time;
This cannot be solved as subtraction of two times in format HHMM because hour has only 60 minutes (eg. 900 - 732 = 168 does not equal to the correct 1 hour and 28 minutes)
This script should work
function pad(num, size) { // num = number which gets the leading zeros; size = number of digits the string will have (in your case 2)
var s = num.toString(); // convert integer to string
while (s.length < size) s = "0" + s; // if number of digits is smaller than requested, add leading zeros
return s; // return the number (as string) with leading zeros
}
var time1 = document.getElementById('indulas').value.match(/.{2}/g),
// split string each 2 characters ("0932" -> ["09", "32"])
time2 = document.getElementById('erkezes').value.match(/.{2}/g),
// day 1 is today, day 2 - 1 adds 24 hours
days = parseInt(document.getElementById('nap').value)-1,
// start date on day 0 at HH, MM
startDate = new Date(0, 0, 0, parseInt(time1[0]), parseInt(time1[1])),
// end date on day 0 + days at HH, MM
endDate = new Date(0, 0, days, parseInt(time2[0]), parseInt(time2[1])),
// subtract dates in milliseconds
diff = endDate.getTime() - startDate.getTime(),
// hour and minute in miliseconds
hour_in_mili= 1000 * 60 * 60,
minute_in_mili = 1000 * 60,
// calculate number of hours in diff time
hours = Math.floor(diff / hour_in_mili),
// calculate number of minutes in the diff time what left after subtracting the hours
minutes = Math.floor((diff - (hours * hour_in_mili)) / minute_in_mili);
/*
if indulas.value = "0932", erkezes.value = "1650", nap.value = "1"
script shows "7:18"
*/
document.getElementById('ido').value = hours + ":" + pad(minutes, 2);
I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
You must understand what Date object represent and how it stores dates. Basically each Date is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
What you really need is:
var diffMillis = nu - tid1;
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
Working fiddle.
I am making an HTML table that should hide certain parts according to the time using JavaScript, for example;
6:30
6:45
7:05
When the current time is equal or greater than 6:30 the first cell should hide.
The way I start this is;
var now = new Date(); // to create date object
var h = now.getHours(); // to get current hour
var m = now.getMinutes(); // to get current minute
And then later;
if (h>=6 && m>=30) {
$('table#truetable tr:first').hide();
}
This does not work (I think the problem is in the last part), as it wouldn't hide this (first) cell in let's say 7:25 as the minute number then isn't greater than 30, which means this way wouldn't work in many other cases.
Can I fix this? Do I need to do it another way?
Compare by minutes:
if( h*60+m/*h:m*/ >= 6*60+30/*6:30*/ ){
}
The easiest way is to handle the case when it's 6 o'clock separately:
if (h > 6 || (h == 6 && m >= 30)) {
// Modify DOM
}
var t = new Date()
undefined
t.getHours()
20
t.getHours()>=6
true
h = t.getMinutes()
51
t>=30
true
This does work. your problem is that you are checking for time and minutes, which mean that if the minutes are lesser than 30 it will return false.
Your if translates to:
any hour bigger than six whose minutes are also bigger than 30
Your if condition should be:
if(h>=6 && m>=30 || h>=7)
or with numbers only
if(h*60+m>= 390)
I wrote a function to convert a time in the hh:mm or hh:mm:ss format to seconds. You can find it below:
function hourConvert(str) {
//this separates the string into an array with two parts,
//the first part is the hours, the second the minutes
//possibly the third part is the seconds
str = str.split(":");
//multiply the hours and minutes respectively with 3600 and 60
seconds = str[0] * 3600 + str[1] * 60;
//if the there were seconds present, also add them in
if (str.length == 3) seconds = seconds + str[2];
return seconds;
}
It is now easy to compare times with each other:
if (hourConvert(str) > hourConvert("6:30")) //Do Stuff
See it in action: http://jsfiddle.net/TsEdv/1/