Why am I getting the wrong minutes from duration? - javascript

I wrote a component with a timer. Two values are transferred to it - the start and end times, from which I get the difference:
const differenceTime = this.endTime - this.startTime
Values are passed in correctly, because:
console.log(
duration,
duration.minutes(),
duration.asMinutes()
)
It shows:
Duration {_isValid: true, _milliseconds: 3931000, _days: 0, _months: 0, _data: {…}, …}
5
65.51666666666667
That is, it proves that my code and values are generally correct. Then why does the minutes() method pass some kind of trimmed number? When it was 69 minutes, this method showed 9. When it was 68 minutes, this method showed 8.

When you are using minutes(), it will literally return your minutes value. That means, if you have time of 1 hour and 5 minutes (65 minutes in total), it will just return 5.

Related

Check if Number in minutes is a hour mark (60..120..180.. 240 mins etc) [duplicate]

This question already has answers here:
What does % do in JavaScript?
(10 answers)
Closed last year.
Question
Figure out if a minute number is the exact number leading into an hour / hours.
Description
I have no code examples, as its something I'm trying to figure out.
I'm trying to build a script that basically returns true or false if the amount of seconds leads into an hour or x hours ; otherwise if not it returns false.
I'm unsure exactly how this should work, as it basically just all the time should check if the amount of minutes - would be the exact minutes to lead into an hour.. (This being 1 hour, 2 hours, 3 hours, 4 hours..... and so on)
I do not need to know how many hours it is or anything; i just need to know if its true or false if the amount of minutes would be exact to Is the amount of minutes an exact hour hour timers.
Expected Workflow examples
The minute number is just a const/let/var input being (example: 59, 60, 120, 300, 673)
If Minute Number is 0-59 Return false
If Minute Number is 60 Return true (Because this would be 1 Hour)
If Minute Number is 60-119 Return false
If Minute Number is 120 Return true (Because this would be exact 2 Hours)
If Minute Number is 121-179 Return false
If Minute Number is 180 Return true (Because this would be exact 3 Hours)
... and so on, basically endless - it just has to return true on any exact is minute an hour part, otherwise false.
My thoughts i had to complete, but not sure
I would guess you would need to check if the minute number is divded by 60 or something like that; but im unsure.
Hope someone is able to help me out, thank you in advance.
You are looking for the modulo (%) operator
function IsOnHour(minutes) {
return minutes % 60 == 0
}
console.log(IsOnHour(59))
console.log(IsOnHour(60))
console.log(IsOnHour(61))
console.log(IsOnHour(120))
Produces
false
true
false
true

Encode a unique string every 5 second using date

I am working on a encryption project, and I basically want to get a different string every 5 seconds regardless from the platform it's being called from.
I can get a unique string every second, and this will give the same thing on any platform
return btoa(new Date().getSeconds().toString() + 'secret');
Every minute
return btoa(new Date().getMinutes().toString() + 'secret');
But, I want to do something similar to this but every 5 seconds, so that the other platform will have enough time (5 seconds) as 1 second is too short, and 1 minute is too long.
Any ideas?
This is not something you can find using Date, but can easily be done by using some math.
const date = new Date();
const time = date.getSeconds() - (date.getSeconds() % 5);
This will give you the seconds in this minute of a multiple of 5.
So every 5 seconds it goes from 0 to 5 to 10 and so on.

How to declare a variable as a time value and add to it

I’m trying to make one of my variable an initial starting time and have the output be an addition to that time based on a number of parameters.
For instance;
I start subtract x from y and get z. Then I take z and divide it from x getting the % of that difference to the original number. Then based on that percentage every 5% represents 5mins. So if i start at 10:00am and the price of hotdog is $10 and if drops to $8 (20% drop) I want to show a 20min addition to 10:00am.
My issue is that when I get to the addition to the original time it goes past 60 min. So instead of it going from 900 to 1010 it goes to 970.
How do I make it count from 60’s like time. Please help. Thanks!
Store everything as minutes (or seconds, days - whatever is most suitable) and convert the values whenever needed:
function convertToHourString (minutes) {
return Math.floor( minutes / 60 ) + ':' + minutes % 60
}
convertToHourString(10); // 0:10
convertToHourString(70); // 1:10

Comparing time using Moment.js in a minute format that doesn't reset on the hour

I am trying to create a count up timer based on an object's modified time (formatted like: 2014-02-19T18:49:15) and comparing it to the current time using Moment.js. But when it reaches 60 minutes, it restarts back to 0. I think this is because I am comparing just the minutes here or at least using math to change the milliseconds to a whole number format? I am not quite sure, I got excited when I got the minutes to format correctly. The difference in minutes is all I want to return. So for example after an hour and a half I want a returned value of '90'.
function() {
return function(entry) {
var elpTime = Math.floor(((Date.parse(moment()) - Date.parse(entry.arrival_time)) / (1000*60)) % 60);
return elpTime;
}
};
Here is an example of the object.
{
patient_id: 198,
arrival_time: "2014-02-19T18:49:15",
last_modified: "2014-02-19T18:49:15"
}
I know I am missing something probably obvious. But any help is appreciated. Thanks!
(Should be noted that I am using this as apart of a filter function in Angular.js. But I stripped it out since I didn't think it was nessacary)
Since you are using Moment.js you can use the built in diff function to return the time period between two moments.
function() {
return function(entry) {
var elpTime = moment(entry.arrival_time).diff(moment(),'minutes');
return elpTime;
}
};
From the documentation:
The supported measurements are years, months, weeks, days, hours, minutes, and seconds.
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.
Example from documentation:
var a = moment([2008, 6]);
var b = moment([2007, 0]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.5

Javascript: Converting a string, ie. "1 hour 2 minutes" to time in seconds

I have found lots of plugins for this sort of functionality with date, such as this although I haven't been able to find something that converts the a string of a time interval ("2 min", "10 seconds", "1 hour and 4 minutes" etc.) to a time in seconds.
Any ideas or plugins you know about? Thanks.
I would write a function that repeatedly matches "(digit+) (timeUnit)" and does the arithmetic in milliseconds because they are more common units. Something like this:
var timespanMillis = (function() {
var tMillis = {
second: 1000,
min: 60 * 1000,
minute: 60 * 1000,
hour: 60 * 60 * 1000 // etc.
};
return function(s) {
var regex = /(\d+)\s*(second|min|minute|hour)/g, ms=0, m, x;
while (m = regex(s)) {
x = Number(m[1]) * (tMillis[m[2]]||0);
ms += x;
}
return x ? ms : NaN;
};
})();
timespanMillis("2 mins"); // => 120000
timespanMillis("10 seconds"); // => 10000
timespanMillis("1 hour and 4 minutes"); // => 3840000
timespanMillis("Foobar"); // => NaN
The trick is to keep the tMillis lookup object in sync with the regex but it shouldn't be too hard; for example, you could construct the regular expression in the closure by joining the properties of tMillis as the source string.
Once you have decided on the format, you need to write a script, that converts your format of time to standard format or just extracts the essential numbers from your format.
After that, you can use the date constructor to parse a date, then write get the seconds from the getTime() method
var d=new Date("October 12, 1987 10:23:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");
I wrote an Open source library MgntUtils in java (not javascript) that answers in part to this requirement. It contains a static method parsingStringToTimeInterval(String value) this method parses a string that is expected to hold some time interval value - a numeric value with optional time unit suffix. For example, string "38s" will be parsed as 38 seconds, "24m" - 24 minutes "4h" - 4 hours, "3d" - 3 days and "45" as 45 milliseconds. Supported suffixes are "s" for seconds, "m" for minutes, "h" for hours, and "d" for days. String without suffix is considered to hold a value in milliseconds. Suffixes are case insensitive. If provided String contains an unsupported suffix or holds negative numeric value or zero or holds a non-numeric value - then IllegalArgumentException is thrown. This method returns TimeInterval class - a class also defined in this library. Essentially, it holds two properties with relevant getters and setters: long "value" and java.util.concurrent.TimeUnit. But in addition to getters and setters this class has methods toMillis(), toSeconds(), toMinutes(), toHours() toDays(). Those methods return long vlaue in specified time scale (The same way as corresponding methods in class java.util.concurrent.TimeUnit)
This method may be very useful for parsing time interval properties such as timeouts or waiting periods from configuration files. It eliminates unneeded calculations from different time scales to milliseconds back and forth. Consider that you have a methodInvokingInterval property that you need to set for 5 days. So in order to set the milliseconds value you will need to calculate that 5 days is 432000000 milliseconds (obviously not an impossible task but annoying and error prone) and then anyone else who sees the value 432000000 will have to calculate it back to 5 days which is frustrating. But using this method you will have a property value set to "5d" and invoking the code
long seconds = TextUtils.parsingStringToTimeInterval("5d").toSeconds();
will solve your conversion problem. Obviously, this is not overly complex feature, but it could add simplicity and clarity in your configuration files and save some frustration and "stupid" miscalculation into milliseconds bugs. Here is the link to the article that describes the MgntUtils library as well as where to get it: MgntUtils

Categories

Resources