JavaScript + Format duration with Moment.js - javascript

I have some JavaScript running in Node. This code dynamically gets a number of seconds. For the sake of this example, I'll choose 180 to represent 3 minutes. I'm trying to format the number of seconds like "3:00" using Moment.js. I'm trying to format the number of seconds using the Moment duration and Moment duration format plugin. My code looks like this:
var duration = 180;
var text = moment.duration(duration, 'seconds').format('mm:ss');
console.log(text);
When I run this, I see text is printed as 00. It's not formatted as I'd expect and I do not understand why. Can someone please explain to me what I'm doing wrong?
Thank you!

Related

How to parse "1h30m" style durations into a Moment.js duration

I would like to try and convert time duration strings to a moment.js duration object. An example of the string format is as follows: "1h30m", which should correspond to 1 hour, 30 minutes, and 0 seconds.
My first thought was to use regex so that I could pull the hours, minutes and seconds but I have a feeling that there's a more efficient way to handle it - the end goal is to use these to calculate how long until a command is run - I saw there was a library called momentjs that I feel could possibly handle this, but the docs don't give a clear way on handling duration formatting in the format that I have in mind. I can provide the code I have written so far, though I don't imagine it would be of much help.
Yes, you can use moment.js to do this - but I'm not sure if it's strictly necessary as it can also be accomplished through simple string manipulation.
String Manipulation Approach:
function parseTimeSpan(timeString) {
let parts = timeString.split("h");
return {
hours: Number(parts[0]),
minutes: Number(parts[1].slice(0, -1))
};
}
JsFiddle Here
Note this will only work with strings that contain both the hour and minute component, and does not support seconds.
Moment.JS Approach:
function parseTimeSpan(timeString) {
return moment.duration("PT" + timeString.toUpperCase());
}
JsFiddle Here
This approach is more robust and handles far more use cases, but is slower and requires an external library.

Transform number of seconds to humanized string in Moment.js

I have a number of seconds (for example 123 sec).
And I need to transform that seconds to humanized string like:
2 minutes 3 seconds
How can I do it with plain Moment.js without any external plugins?
I tried to do it with that code:
let test = document.querySelector('#test')
let time = moment.duration(123, 'seconds')
test.innerHTML = `
${moment.duration(time.minutes(), 'minutes').humanize()}
${moment.duration(time.seconds(), 'seconds').humanize()}
`
But the output is:
2 minutes a few seconds
P.S That would be great if there will be used Moment's locales for easy switch to another language.
Thanks!
How can I do it with plain Moment.js without any external plugins?
Why?
You're already using Moment itself... You can use the moment-duration-format plugin and so easily get exactly what you want.
moment.duration(123, 'seconds').format("m [minutes] s [seconds]");
// "2 minutes 3 seconds"
Or auto-localize it...
moment.duration(123, 'seconds').format("m __ s __");

Using moment.js how do I give a specific format for a duration

Given a duration of a number of seconds coming from an API as duration_seconds = 86485.
(1 day, 0 hours, 1 minute, 1 second)
I was going to use moment.js to convert this into formatted duration as follows:
1. {d} {hh}:{mm}:{ss} (1d 00:01:01)
2. {d}d {hh}h m{mm} s{ss} (1d 04h 30m 23s)
I would also like to ensure the following:
Days are trimmed if days is 0 (00:01:01 - for 1 minute 1 second)
hh:mm:ss are never trimmed, 1 second shows as 00:00:01.
I can create the duration like this:
moment.duration(duration_seconds, 'seconds')
The humanize function is not suitable as it approximates.
I can also write my own with:
duration.get('d')
duration.get('h')
duration.get('m')
duration.get('s')
I can't seem to find a built in function but I assume this would be an obvious one? Is there something I am missing, otherwise I can PR one into moment library.
This seems to imply that the function still does not exist:
Using moment.js, How can I simplify a duration to its most simplified form?
The moment-duration-format plugin can assist you with this.
// your input
var duration_seconds = 86485;
// create a moment-duration object
var duration = moment.duration(duration_seconds, 'seconds');
// format the object with a string
var formatted = duration.format('h[h] m[m] s[s]');
// displaying the output here
document.getElementById('output').innerHTML = formatted;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
<div id="output" />
Note that by default it will omit units that are not relevant, so if your input is 3, it's just going to say "3s", not "0h 0m 3s".
If you want to change this behavior, set trim:false, per the documentation. For example, to get the format you mentioned in comments, use:
.format('hh:mm:ss', { trim: false })
Maybe you can try this?
moment(duration).format("DD MMM YYYY hh:mm: a")
Though you might have to convert your seconds to milliseconds. This can be done by saying duration * 1000.
Found from this answer: Moment js convert milliseconds into date and time

Jquery Countup show only hour and minutes

I'm using the following Jquery countup script. I'm trying to show only hours and minutes but I can't figure out how to do that. And I'm trying to show the hours and minutes with 2 digits with leading zeros.
Could somebody explain to me how I could achieve this?
This is the snippet I found in above lib:
$(document).ready(function(){
$('#jq_count_up').countUp({'lang':'en', 'format':'full', 'sinceDate': '22/07/2008-00::00'});
});
Now in here, change the value of format. You should follow this lib docs to find out matching format.
Just happened to look into this js file. They have clearly shown the example for this as well...
//example: $.countUp({ 'sinceDate':'01/01/2011', 'lang':'en', 'format':'day' });
//date format: dd/mm/yyyy-hh:mm:ss
//available langs: english (en), turkish (tr), deutsch (de), spanish (es)
//format options: full, day, seconds

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources