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.
Related
I'am using moment.js for formatting date, time and duration.
From api I get e.g. this string "1540034040". It should be converted to 13:14
In my React app I have a function which returns return moment(time, 'HH:mm').format('HH:mm');, but then I get another time 15:40? I see there is a package moment timezone. But I don't want to install another package.
Is there somehow a way to fix this with just moment or javascript, without installing another package?
The time string you are passing ("1540034040") is having 10 digit long. the moment package is expecting this kind of string in millisecond format( 13 digit long string ).
For example "1540034040000".
For this given string the time will get converting to some other past date with different time because you have passed second instead of milliseconds.
For debugging you should try to print whole date and time of the given string ("1540034040") instead of just hours and minutes. it will make things more clear.
You should try passing the milliseconds. i am sure it will fix the issue.
I got this working by:
first transform my string to a number so I am able to use unix() and then format with moment().format()
const timeString = time;
const timeNumber = parseInt(timeString, 10);
return moment.unix(timeNumber).format('HH:mm');
I'd like to use momentjs to use a given amount of seconds (e.g. 65) and format that to minutes and seconds (so in the case of 65 seconds it should format it to '01:05'). I've looked around the momentjs docs and also here but I couldn't quite get to the right solution. I know there's a way to do this with just pure JavaScript, but I'd like to use momentjs for this.
Any suggestions?
If you insist on doing this using moment.js, you can do something like this:
Start with a 00:00:00.000 time and add seconds, minutes, etc. to it.
Here is an example:
const result = moment("00:00:00.000", "hh:mm:ss.SSS").add(65, "s").format("mm:ss");
console.log(result);
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
The problem is that since this is the time of a date, when you add 24 hours to it, you'll end up with 00:00:00 instead of 24:00:00.
I need to format two moment objects to display a time range to users, eg:
6:45PM-9:30PM
I know I can get this with
`${time1.format('h:mmA')}-${time2.format('h:mmA')}`
but I want to suppress minutes when either the start or end time is on the hour, eg:
6:45PM-10PM (instead of 6:45PM-10:00PM)
7PM-9:30PM (instead of 7:00PM-9:30PM)
7PM-10PM (instead of 7:00PM-10:00PM)
I can check to see if the minutes are 0 before and change my formatting string based on that, but that seems inelegant I'd like to do this only using .format if possible. Haven't found anything in the formatting docs about this.
.format does not provide that you want inbuilt. Rather you can use string replace function instead.
`${time1.format('h:mmA').replace(":00","")}-${time2.format('h:mmA').replace(":00","")}`
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
I need to run a JS function at midnight of a given date. Is that something possible with JS, mine is a node app and i was looking at the laterJS library but not sure how exactly i can use the recurse function from laterJS library for this need. It would be nice to use laterJS lib for this requirement as opposed to using something like node scheduler.
Please share any thoughts/ideas.
With this question i'm particularly looking to use a library that can do this like laterJS and not a CRON kind of thing that node scheduler provides.
The value of given date is completely dynamic and it could be any date in MM/DD/YYYY format so fundamentally i cannot hard code the value in later.parse.text as 25th day of the month etc.. but i can hard code the time as 11:59 pm, given the fact that the date is dynamic in MM/DD/YYYY format can i use later.parse.text('at 11:59 pm on the "+DD+"th day of "+MM+" in "+YYYY+"'); something like this...
So tried some thing like this, Constructing a later.parse.recur() to run on a specific day/month/year/time but not sure how to handle the time.. Any help?
May be Cron expression section of Later.js is what you are looking at. It is meant for exactly this sort of thing.
You can pick the relevant one from below -
If you want on a specific day of the month, the expression will be something like
var complexSched = later.parse.recur()
.on(15).dayOfMonth().onWeekday().on(2).hour()
If it is a repeating schedule, it will be something like
var textSched = later.parse.text('at 10:15am every weekday');
A cron expression will be something like this-
var cronSched = later.parse.cron('0 0/5 14,18 * * ?');