Number of hours to HH:MM with Moment.js (or without) - javascript

I have very simple problem, but couldn't find good simple DRY solution. I want to convert number of hours to HH:MM format. My try with Moment.js is:
var hours = 10.5
var hour_string = moment(hours*3600*1000).format('HH:MM')
But unfortunately I get:
"11:01"
and have no idea why. Of course my wanted result is "10:30".
I'd like just do it in the easiest way, similar as I can do in Rails:
Time.at(hours*3600).utc.strftime("%H:%M")
Any ideas?

Okay, I found the reason. "MM" means months, not minutes, which are "mm". And the hour shift was caused by timezones, which we can omit using the utc function. The final solution is:
moment.utc(hours*3600*1000).format('HH:mm')

Related

Moment JS function `moment()` returning a different date/time on different devices

In my React Native app, I'm calculating the difference between a given time and the current time using moment JS. My code to calculate minsLeft, the difference between the two times, is:
let minsLeft = moment.duration(moment(request.AcceptedDate, "DD-MMM-YYYY h:mm:ss A")
.subtract(new Date().getTimezoneOffset(), 'minutes')
.add(request.ETA, 'minutes')
.diff(moment())
)
request.AcceptedDate was 3-May-2020 04:37:31 PM, and on that day (May 3) at 5pm I was getting a result of 23 minutes, as expected. On some devices though, I was getting values of negative several thousand minutes. The numbers were consistent with the app calculating the current date as 05/03/2021 instead of 03/05/2021, as if the moment() function returns something different on different devices.
Has anyone run into anything like this and know where this discrepancy might be coming from?
I also had the same problem. Turns out the moment() function depends on the timezone, date, and time set on the device. As you change your time or date or timezone, you get different results.
var now = "04/05/2021 11:00:00"; //new Date();
var then = "03/05/2021 11:20:00";
var s = moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss");
console.log("s:", s);
//output: 23:40:00
Get difference between two times using moment. Hope it is works for react native. i tried it in react.
The issue is with timezones and formatting.
Considering your request to be:
let request = {AcceptedDate: '06-May-2021 11:03:28 AM', ETA:60}
As per your comment AcceptedDate is of the format DD-MMM-YYYY h:mm:ss A and is already in UTC time.
Here are 2 different approaches to solve your issue:
Approach 1: Using new Date().getTimezoneOffset()
let minsLeft = Math.abs(moment(request_TimeStamp.AcceptedDate).subtract(new Date().getTimezoneOffset(), 'minutes').add(request_TimeStamp.ETA, 'minutes').diff(moment(), 'minutes'))
Approach 2: Using moment().local()
let minsLeft = Math.abs(moment(request_TimeStamp.AcceptedDate).utc(request_TimeStamp.AcceptedDate).local().add(request_TimeStamp.ETA, 'minutes').diff(moment(), 'minutes'))
I have created a Snack with both the above approaches
Kindly Vote and Flag my solution if it helped you in any way. Cheers!

How to work with Moment.js to return time in a 24-hours format when adding to it?

I get hours as strings in my app, e.g. "2230". I would like to be able to add minutes to it, so as to simulate the time that it will be after those minutes have been added to it, e.g.
//"2230" + "60"mins = "23:30"
//"2230" + "180"mins = "02:30"
I read that Moment.js could be a solution to this, but I couldn't figure out:
what the right way to format the hours initially is with moment("2230").format()
how to add minutes to it
how to make it behave like a 24-hour clock when adding to it
Moment is a great tool for doing this. It takes some syntax tricks to get it right, but I think this is what you're looking for:
moment("2230", "HH:mm")
.add(60, "minutes")
.format("HH:mm")
Feel free to play around with it here:
https://codesandbox.io/s/proud-pine-lz0fs?file=/src/index.js
As you can see, as long as your time string is always 4 characters long, moment can extract the HH:mm format, then you can add minutes, and then format the final output to HH:mm again.
Here are 2 great resources:
https://techstream.org/Bits/Javascript/Javascript-Parse-time
https://flaviocopes.com/momentjs/
Hope that helps!
First you have to split this string to get the hours and minutes from it.
const s= "2230"
const hour = s.substring(0,2);
const min = s.substring(2,4);
After that you can easily pass this hours and min to a moment.
const time = moment()
.set({"hour": hour, "minute": min})
.add(60, 'minutes')
.format("HH:mm");
the .set is to set the time (hours minutes)
the .add is to add the minutes you wanted to add
the .format is to format the output as you pleased,
NOTE the capital "HH" means 24/h clock while "hh" means 12/h clock

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.

MomentJS is sometimes adding the wrong amount of hours

So what i'm simply trying to achieve a feature where i add X.X amount of hours to a 24h time. The issue is for the time 00:00, an incorrect amount of hours is added
The code i wrote works for the most part. It works for every possible time except 0:00.
If i have 01:30 and i add 1h it gives me 02:30. If I have 02:30 and i add 1.5h it gives me 04:00.
So heres this issue. When i have 00:00 and i add 1h i get 01:06...seems to make no sense and i was hoping someone with more momentJS experience might have some thoughts or ideas on the matter. Heres the code
If i have 00:00 and have 3.5 i get 03:06. This all only seems to happen when i start with 00:00. Kind of driving me crazy
console.log(timesheetRows[i][p]); //prints 0:00
console.log(Number(hours)); // prints 1
timesheetRows[i][p] = moment.utc(timesheetRows[i][p], 'hh:mm').add(Number(hours), 'hours').format('HH:MM');
You're using the wrong formats, hh stands for 12 hours and MM stands for two digits month number.
Use something like this:
moment.utc(timesheetRows[i][p], 'HH:mm').add(Number(hours), 'hours').format('HH:mm');

YYYY-MM-DDTHH:mm not getting am/pm momentjs

I know this type of question is not really apropiated, but I'm stuck on it and some help would be apreciated it. I have the following date:
2018-04-26T08:19:30+02:00
But when I try to get the Hours and Minutes, the result I get is:
20:19 p
What I'm doing is the following:
let momentDay = (moment(el.time,'HH:mm a').format('HH:mm a'));
I don't know how I could get the real time, the one should give me: 08:19 instead of 20:19
Thanks
You should use hh for twelve hour time, rather than HH, which is for 24 hour time.
Also, if el.time is a datetime object, or a recognizable unambiguous date format (as yours is), then you don't need to specify a format in the constructor:
let momentDay = moment(el.time).format('hh:mm aa');

Categories

Resources