How to convert a moment object into a duration in seconds? - momentjs

I found lots of info on converting a duration object into various formats but it's harder to find info on converting a moment object into a duration in seconds.
This answer offers the following solution: myVar = moment.duration(myVar).asSeconds()
However it doesn't work in my case, myVar is in MM:SS format not HH:MM:SS format so I'm getting an aberrant result. Any idea how to adapt it to my situation?
EDIT: here's some code
this.totalTimeSimulation = moment(lastActionEndTime, 'mm:ss').add(additionalTimeDuration, 'seconds').format('mm:ss')
this.totalTimeSimulationInSeconds = moment.duration(this.totalTimeSimulation).asSeconds()
console.log(this.totalTimeSimulation)
console.log(this.totalTimeSimulationInSeconds)
In console I see:
04:00
14400
Should be:
04:00
240
Because 4 minutes equals 240 seconds, not 14400 seconds. Moment.js thinks I'm giving it a duration in HH:MM:SS format when actually I'm giving it in MM:SS format.

Moment threats input like 04:00 as HH:MM
The format is an hour, minute, second string separated by colons like 23:59:59. The number of days can be prefixed with a dot separator like so 7.23:59:59. Partial seconds are supported as well 23:59:59.999.
moment.duration('23:59:59');
moment.duration('23:59:59.999');
moment.duration('7.23:59:59.999');
moment.duration('23:59'); // added in 2.3.0
You can prefix your input with 00: or use moment.duration(Object) constructor using minutes and seconds keys:
const totalTimeSimulation = '04:00'
const totalTimeSimulationInSeconds = moment.duration('00:' + totalTimeSimulation).asSeconds()
console.log(totalTimeSimulation)
console.log(totalTimeSimulationInSeconds)
const parts = totalTimeSimulation.split(':')
const seconds = moment.duration({
minutes: parts[0],
seconds: parts[1]}).asSeconds()
console.log(seconds)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Related

Groovy: Date and Time comparisons with a slight delay

So I have the following script:
import groovy.time.TimeCategory
def dueDate = context.expand( '${Test 4 - create user task#Response#$[\'_embedded\'][\'userTaskDtoList\'][0][\'dueDate\']}' )
def date = new Date(messageExchange.getTimestamp())
use(groovy.time.TimeCategory){
after24Hours = (date + 24.hours).format("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone('UTC')) }
assert dueDate == after24Hours
What I'm trying to do with this is take the date and time from a REST request (dueDate - which comes in UTC format and with a 24h delay) and create a new date and time from the timestamp of the moment when that request has been sent, which is registered from my system. I then convert that time to UTC to accommodate the format from dueDate and add 24h to it. At the end I verify that the date and time from dueDate and after24Hours is the same.
The output does return the same time but in certain cases if there is a delay between the time the request is being sent and the time is received then the assertion will fail. This depends on the server, usually there is a difference of like 1 millisecond but I'm thinking that if the server will be slower at some point this will definitely be bigger.
What could I do to allow some margin of error in the assertion, maybe like a few seconds or even a couple of minutes?
Ok, so I managed to do this:
import groovy.time.*
def dueDate = context.expand( '${Test 4 - create user task#Response#$[\'_embedded\'][\'userTaskDtoList\'][0][\'dueDate\']}' )
def date = new Date(messageExchange.getTimestamp())
use(groovy.time.TimeCategory){
after24Hours = (date + 24.hours).format("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone('UTC'))
def date1 = Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", dueDate)
def date2 = Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", after24Hours)
TimeDuration difference = TimeCategory.minus(date2, date1)
log.info date1
log.info date2
assert difference < 2.minutes
}
The script seems to work and it does return an error only if the time is longer than the one I've set in the assertion.
Unfortunately I have another issue now.
For some reason, my date output looks like this:
Fri Oct 01 16:24:10 EEST 2021: INFO: Sat Oct 02 13:24:10 EEST 2021
Which is not the correct format. That date should appear in the Zulu format, after all when I parsed the dates that was the format that I used.
Am I missing something?
What could I do to allow some margin of error in the assertion, maybe
like a few seconds or even a couple of minutes?
Instead of asserting that they are equal, you could assert that the difference between them is less than a threshold that you get to define.
If you use something like AssertJ, and I'd recommend you do, then you can do something like the following:
assertThat(dueDate).isCloseTo(after24Hours, within(1, ChronoUnit.MINUTE));
This will give a small margin to the comparison of the dates, and should fix your issue.

Why is moment.js date is 50 years ahead?

Using moment to format a date retrieved from a firestore timestamp. However the date is off by at least a day, and at most, a few months. and the year is off by 50 no matter what.
Here is the firestore timestamp
EDIT: Here is whats logged from lastMsg.seconds:
1581372232
I retrieve the time in seconds in a FlatList's renderItem:
renderItem={({ item, index }) => {
return (
<Components.InboxItem
title={item.withName}
subtitle={item.lastMsg.seconds}
img={item.withImg}
/>
);
And finally inside the component I use moment like so:
const date = moment()
.utc()
.startOf('year')
.seconds(props.subtitle)
.format('MMMM DD YYYY');
While ive tried multiple format configurations, the one that gets it closest to accurate is with .startOf("year"). Even then, date is being displayed as "February 09, 2070". If .startOf() is changed to "month", "day", or "hour", the date gets changed to sometime in march. How can this be fixed to display the date as in firestore?
Looking at the https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp we can either get JS Date object or use the toMillis method to get milliseconds.
Now the simple moment.js api for converting timestamp to moment object is given here https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/
moment(Number);
Now you can apply format on the moment object like below:
moment(Number).format(String);
Your issue with wrong date is may be due to the use of utc and seconds together and not passing timestamp to moment()
Use moment.unix():
const props = {
subtitle: 1581372232
};
const date = moment
.unix(props.subtitle)
.format('MMMM DD YYYY');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
because item.lastMsg.seconds is
The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z

Converting time format in simpleWeather.js

I want to convert the time from the standard 12-hour reading to the 24-hour one in simpleWeather. When I try to do it, it returns the time in the Unix epoch format.
$(function sunset(){
var sunset=
$.simpleWeather({
location:'Dalol,Afar',
woeid:'',
units:'f',
success:function(weather){
var Sunset= moment(weather.sunset, "HH:mm:ss");
html='Sunset: '+Sunset;
$('#sunset').html(html);
}
});
});
I had contacted the developer on how to do convert it using moment.js, but he didn't say much more than that. How can the code be corrected to display the desired format?
You need to first parse and then format the weather.sunset with the right formatting:
var sunset = moment(weather.sunset, ["h:mm A"]).format("HH:mm");
simpleWeather.js returns the sunset as "5:31 pm" so the corresponding moment format to parse this date is h:mm A, where the A captures the pm/am. To format it in the 24-hour notation, format("HH:mm") will do the job.

Displaying local time from ISO 8601 string with Momentjs

I want to display the local time from an ISO 8601 string using momentjs.
There is a discrepancy of minutes when I convert an ISO string using different date formats. If I use 'MM/DD/YYYY HH:mm', the minutes is correctly displayed. If I use 'ddd, MMM Do HH:MMa', 11 minutes is added (in my case).
My sample js (babel) code:
let today = moment('11/09/2016 00:00', 'MM/DD/YYYY HH:mm').toISOString();
//today = 2016-11-09T08:00:00.000Z
let formatted = moment(today, moment.ISO_8601).format('MM/DD/YYYY HH:mm');
//formatted = 11/09/2016 00:00
let formatted2 = moment(today, moment.ISO_8601).format('ddd, MMM Do HH:MMa');
//formatted2 = Wed, Nov 9th 00:11am
I would prefer using the second format. Can someone explain why there is a discrepancy?
Please see this fiddle: https://jsfiddle.net/anudhagat/8fgtjbc7/3/
I caught my silly mistake. I have capitalized the minutes in the second format, using MM makes it display months instead of minutes.

Wrong time difference with momentjs diff function

i'm trying to calculate the difference between two UTC Datetime Strings with angular-momentjs like shown below:
var start = "1970-01-01T11:03:00.000Z";
var end = "1970-01-01T11:15:00.000Z";
var duration = $moment.utc($moment(end).diff($moment(start))).format("hh:mm");
when i execute the code above, the duration should be 00:12 but actually it is 12:12. I don't understand why and how to fix it.
You are actually creating a moment.js object for 1970-01-01T00:12:00.000Z, then getting the time as hour and minutes. The token "hh" is for 12 hour time, so you're seeing "12" for 12am. If you want to see 00:12, use the token "HH" which gives 24 hour time: 00:12.

Resources