I need to convert a complete hour by hour into %, but I am not sure if moment is able to do that.
Eg.:
I do have
let start = 08:00:00
// until
let end = 09:00:00
This is equal: 100%, but I receive an information from frontend value:
let data = 08:25:40
I need to know how much percent of hour have been passed from start, until the end.
I do have an workaround, but this is a little bit like a trick not a real solution.
Does anybody knows if JS has a library that can do this for me, easily?
Thanks.
Count the time difference from start to end and from start to your data in milisecond, then do simple math. Use diff method to calculate the time difference in milliseconds.
Here is a similar code snippet:
let start = 08:00:
let end = 09:00:00
let data = 08:25:40
const mStart = moment(start)
const mEnd = moment(end)
const mData = moment(data)
const percentile = 100.0 * mData.diff(mStart)/mEnd.diff(mStart)
Related
I am trying to show the remaining time left after the user inputs their answer.
so it's suppose to be like this.
When does that course start? 2022-09-05 (user input)
Today it is 32 days left until the course starts
I dont think its suppose to be that complicated but I cant make it work, I keep getting NaN or that it just isnt working.
I have checked MDN but I just dont get it.
The code looks like this.
function start(timePassedIn) {
return `Today it is ${timePassedIn} days left until the
course starts`;
}
const course = prompt("When does that course start? ");
const starting = start(course);
console.log(starting);
I removed all my attempts at the date so that you can give me fresh input.
Appreciate all the help I can get.
Can you try this.
function start(timePassedIn) {
return `Today it is ${timePassedIn} days left until the
course starts`;
}
function getDateDifference(inputDate) {
const date1 = new Date(inputDate);
const date2 = new Date();
const diffTime = Math.abs(date1 - date2);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
}
const course = prompt("When does that course start? ");
const starting = start(getDateDifference(course));
dates can be stored in two ways in a program:
as a String, for example "October 10th" or "2022-08-01" or "09/11"
as Date Objects. You already found the documentation for Date in MDN.
we use Strings for input and output, and Date Objects for computation like the difference between two dates.
If I understand you correclty, your program should
ask the user when the course starts
compute how many days are left until the course starts
output the number of days
When you try to program this step 2 is the complicated one:
1. ask the user when the course starts:
`const course = prompt("When does that course start? ");`
course will contain a string with the date. maybe you would be
better off to ask for day and month seperatly?
const month = prompt("When does that course start? Please enter the month as a number");
const day = prompt("When does that course start? Please enter the day as a number");
2. compute how many days are left until the course starts
a) convert the input into a Date object.
b) get a date object of the current date
c) compute the difference and convert to days
I am trying to setup a interval to run every morning at 0730. I am trying to use momentjs to accomplish this.
e.g:
current time - 0730 = how long to wait until it is time to run the function.
For some reason no matter how I manipulate the moment it seems to come back with some wonky math. For example it is currently 0616 in the morning and when I attempted to get this to do the math it came back with a 6hr difference not just over an hour.
var endOfShift = moment('0730', 'HHmm').format(),
now = moment().utcOffset(-8).format(),
diff = moment(now).local() - moment(endOfShift).local();
console.log(endOfShift); // => 2019-12-20T07:30:00+00:00
console.log(now); // => 2019-12-20T06:11:38-08:00
console.log(diff); // => 24098000 milliseconds = 6.6938888889hrs
I have tried removing the utcOffset from now which then the out put for the time/date incorrect. I have tried adding utcOffset to the endOfShift variable. No matter how I mess with the utc it still seems to = around 6hrs when it should be about 1ish. I have tried just removing the utcOffset from everything and just let it do its thing and it still gets the math wrong.
I have also tried moment's diff method w/ similar results.
What am I missing?
-Adam
I think you can achieve this with something like this
const now = moment();
let targetTime = moment('07:30', 'hh:mm'); // could be in past or in future
if (targetTime.isBefore(now)) {
targetTime = targetTime.add(1, 'day'); // add one day if waiting for tomorrows time
}
const diff = targetTime.diff(now);
console.log(diff);
const otherDiff = targetTime - now;
console.log(otherDiff);
The values for diff and otherDiff should be equal so it's up to you which one you prefer.
I have an array of 2 strings, both of which are in Unix time.
[1484930449590,1548002449590]
Converting these back into human readable time gives me today's date and the date 2 years ago.
However, when I parse both of these timestamps with MomentJS:
const start = moment(timeRange[0])
const end = moment(timeRange[1])
I receive the following values:
moment("2001-01-01T00:00:00.000")
moment("2001-04-01T00:00:00.000")
For some reason, momentJS converts both of the timestamps to the year 2001, even though the years should be 2019 and 2017.
Parsing the strings first does not make things better:
const start = moment(parseInt(timeRange[0]))
const end = moment(parseInt(timeRange[1]))
Now start and end are:
moment("1969-12-31T19:00:00.001")
moment("1969-12-31T19:00:00.004")
Does anyone know what is going on?
I tried the following solution:
console.log(timeRange)
const start = moment(parseInt(timeRange[0]) / 1000)
console.log(start)
const end = moment(parseInt(timeRange[1]) / 1000)
console.log(end)
but nothing changed:
1484931697215,1548003697215
moment("1969-12-31T19:00:00.000")
moment("1969-12-31T19:00:00.000")
Update:
The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.
Your timestamp is in milliseconds, not in seconds. Try dividing by 1000 first:
const start = moment(parseInt(timeRange[0]/1000))
const end = moment(parseInt(timeRange[1]/1000))
That should give you the correct date
The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as part of a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.
The solution was to reconvert the timeRange back into an array:
const times = req.query.timeRange.split(",")
const startDate = moment(parseInt(times[0]))
const endDate = moment(parseInt(times[1]))
Im trying to convert duration in seconds to human friendly output using moment js and combination of duration and format.
Im getting the duration in seconds and then formatting it like so:
const value = 337650
const duration = (durationSeconds) => {
const duration = moment.duration(durationSeconds, 'seconds')
return moment.utc(duration.asMilliseconds()).format('D [days] HH:mm:ss')
}
console.log(`Duration: ${duration(value)}`)
outputs
"Duration: 4 days 21:47:30"
JSBin here
The problem I have is that it seems wrong. Online services like https://www.tools4noobs.com/online_tools/seconds_to_hh_mm_ss/ shows one day less.
Im not sure what library/algorithm these services are using and if they are showing the correct time elapsed or moment js.
Any ideas greatly appreciated!
You seem to be converting the duration into an epoch time, then formatting it, which will be wrong.
Take a look at this Moment issue for details about duration formatting. https://github.com/moment/moment/issues/1048
Simple formatting can be done using the humanize method:
let value = 337650
let duration = moment.duration(value, 'seconds')
duration = duration.humanize()
console.log(duration)
"4 days"
Fore more sophisticated formatting you may want to dive into: https://github.com/jsmreese/moment-duration-format.
try something simple:
var x = 337650%86400;
var days = (337650 - x)/86400;
var y = x%3600;
var hours= (x-y)/3600;
var sec = y%60;
var mins=(y-sec)/60;
alert(days + ' days ' + hours+':'+mins+':'+sec)
You can use the moment-duration-format plugin to format durations, the previous approach (creating a new absolute date from a duration) is not going to work. When you add 337650 seconds to the Unix Epoch start, you get January 4, 1970, 21:47:30, which is why you're seeing the day as 4.
As a further example of how this will go badly wrong, imagine we need to format a duration of, say, 2700000 seconds. This will give us an output of "1 days 06:00:00". Why? Because it's equivalent to February 1 1970, 06:00. (The real result will be 31 days, 06:00:00).
I don't think we can blame the authors of moment.js (they've done an amazing job), it's just not using the format function on moment.js as it is supposed to be used.
By using the format function from moment-duration-format, we're formatting as a duration rather than as an absolute time and we get the right result!
momentDurationFormatSetup(moment);
const value = 337650
const duration = (durationSeconds) => {
const duration = moment.duration(durationSeconds, 'seconds')
return duration.format('D [days] HH:mm:ss');
}
console.log(`Duration: ${duration(value)}`)
document.getElementById('output').innerHTML = `Duration: ${duration(value)}`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
<div id="output">
</div>
JSFiddle: https://jsfiddle.net/t07ez8o4/9/
I am trying to calculate how many minutes a worker works from the input starting and ending time(e.g. 10:30 am to 3:30pm). Could u guys help how to calculate them? Could u check my code and correct them? I am very new in Javascript.
function myFunction(){
var sTime=document.getElementById("startTime").value;
var eTime=document.getElementById("endTime").value;
var diff = sTime-eTime;
var result= diff.getMinutes();
document.getElementById("demo").innerHTML=result`;
https://jsbin.com/bolapox/edit?html,output
You will need to turn the users input into a usable format with Date().parse(input). This returns the number of milliseconds since 1 January, 1970, 00:00:00, local time.
You can then take the difference in milliseconds and convert them into minutes.
var sTime=Date().parse(document.getElementById("startTime").value);
var eTime=Date().parse(document.getElementById("endTime").value);
var diff = eTime - sTime;
var result = diff / 60000;
You should consider Moment.js, here yiou can find some examples:
http://momentjs.com/docs/#/durations/