Get current time in seconds using moment.js - momentjs

I am trying to use moment.js to get the current time in seconds. I am really struggling, and apologize for asking what is probably a simple problem.
I have this so far:
const time = await moment().format("hh:mm:ss");
// current time: 11:17:21
expires_in:'3599' (string)
The expires_in is provided from an api call that is given to me in seconds. For example, 3599 (which is about an hour when converted from seconds to minuets).
I want to get the current time (from the client) convert that to seconds.
Then I'd like to add the expires_in to the current time. If that time is > then the current time, I know I need to request a new token.
Thank you for any suggestions!

You can use add method to add expires_in seconds to your time.
const date = moment(),
curr = +moment(),
time = date.format("hh:mm:ss"),
expires_in = '3599',
newTime = date.add(expires_in, 'seconds').format("hh:mm:ss"),
expires = +date.add(expires_in, 'seconds');
console.log(time, newTime);
console.log(curr, expires, curr > expires);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

Related

How to create a momentJS object with a specfic time and a specific timezone(other than the default local time zone)?

I will receive an string(with time and date) from the frontend. The string format is this "2021-08-16T23:15:00.000Z". I intend to declare a moment object with the input string, along with a specific timezone(other than the local one).
import moment from "moment";
import "moment-timezone";
// The input string I receive from the frontend.
let strTime = "2021-08-16T23:15:00.000Z";
console.log(strTime); //2021-08-16T23:15:00.000Z
let time = moment.tz(strTime, "YYYY-MM-DDTHH:mm:ss.SSSZ","America/Boise");
console.log(time); // Moment<2021-08-16T17:15:00-06:00>, undesired value
let UTCtime = moment.utc(time);
console.log(UTCtime);
As far as what I understood from this question, console.log(time) should output a moment object of time 23:15:00, but with timezone "America/Boise".
What I intend is time to have the same time i.e "23:15:00.000", with "America/Boise" as timezone.
So that when I later convert that time to UTC, I need to get the right value w.r.t the timezone "America/Boise" and not my local timezone. How can I do this.
I figured out a solution.
const momenttz = require("moment-timezone");
const moment = require("moment");
// The input string I receive from the frontend.
let strTime = "2021-08-16T23:15:00.000Z";
console.log(strTime); //2021-08-16T23:15:00.000Z
let time = moment.utc(strTime);
time.tz("America/Boise", true);
console.log(time.tz());
console.log(time); // Moment<2021-08-16T23:15:00-06:00>, desired value
let UTCtime = moment.utc(time);
console.log(UTCtime); // Moment<2021-08-17T05:15:00Z>
In the above code, at console.log(time),time has the value "23:15:00.000" with required timezone "America/Boise". This makes it possible for you to get the right value , when you later convert it to UTC.
This is made possible by passing an optional second parameter to .tz mutator of moment-timezone as true which changes only the timezone (and its corresponding offset), and does not affect the time value.
time.tz(timezone, true);
A sample example of using this is given in the answer code above.
You can read more about it here in the Moment Timezone Documentation

How to find the 24 hours difference based on Trip booked time

From the API, I'm getting Trip booked Timezone(PST), Date-Time(2020-07-10 16:00:00). Now I want to check the 24 hours time difference with the user browser current time and display Cancel button otherwise, we need to hide the button. What I have done below is I'm passing trip booked time-2020-08-10 16:58:00 and booked timezone-PST which is getting from API then I'm finding the currentDate and taking the difference using the diff method. But I'm not getting current values. Any Help?
const departureDateWithTimeZone = moment.tz('2020-08-10 16:58:00', 'PST');
const currentDate = moment().format();
const diff = departureDateWithTimeZone.diff(currentDate, 'h');
Docs state that the last argument in moment.tz should be a time zone identifier.
Use America/Los_Angeles (or any other correct tz identifier) instead of PST:
const departureDateWithTimeZone = moment.tz('2020-08-10 16:58:00', 'America/Los_Angeles');
const currentDate = moment();
const diff = departureDateWithTimeZone.diff(currentDate, 'h');
console.log(`Current date: ${currentDate.format('YYYY-MM-DD HH:mm:ss Z')}`);
console.log(`Departure date: ${departureDateWithTimeZone.format('YYYY-MM-DD HH:mm:ss Z')}`);
console.log(`Diff in hours: ${diff}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>

How to add minutes in moment js with a HH:mm format?

How do I add minutes to this. I followed the documentation but somehow this is not working:
var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HHmm').format("HH:mm");
time.add(7,'m');
Only the last line is not working, but should be right according to the documentation. What am I doing wrong?
format returns a string, you have to use add on moment object.
Your code could be like the following:
var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HH:mm');
time.add(7,'m');
console.log(time.format("HH:mm"));
Note that you can create a moment object using moment(Object) method instead of parsing a string, in your case:
moment({hours: hours, minutes: minutes});
As the docs says:
Omitted units default to 0 or the current date, month, and year
You can use IF condition to see if minutes < 10
to add "0" like 07,08
var d = new Date()
var n = d.getMinutes()
if(n<10)
n="0"+n;
But watch out you will have to slice that zero if you want to increment.

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.

Get the minutes that have elapsed through moment diff

I'm trying to get the difference in minutes between two timestamps
I have a timestamp that looks like this to begin with
'15:44:06'
And when I want to find the time elapsed I create a new moment timestamp
var currentTimestamp = Moment(new Date()).format('HH:mm:ss');
Which returns this
'15:42:09'
I then attempt to get the difference like so
var duration = Moment.duration(Moment(currentTimestamp,'HH:mm:ss').diff(Moment(userTimestamp,'HH:mm:ss')));
And then attempt to get it in minutes
var elapsedTime = duration().asMinutes();
console.log(elapsedTime);
But in the console when I log it I get this error
var elapsedTime = duration().asMinutes();
^
TypeError: object is not a function
I got most of this code from this stackoverflow
You can get the diff by using the moment constructor properly.
First, when you initialize your time stamp, you should use the following format:
var timestamp = moment('15:44:06','HH:mm:ss');
Second, when you want to use the diff function with the current time you should user it like so:
timestamp.diff(moment());
Then, the given number can be converted to minutes with .asMinutes() (the first )
for further information you should read the official docs here.
You can also try this with the lastest moment.js
var start = moment('15:44:06','HH:mm:ss');
var minutesPassed = moment().diff(start, 'minutes');
This question is getting a little bit old, this answer just bring the state up to date with a solution the question was looking for:
const startDate = moment();
...
elapsedDuration = moment.duration(moment().diff(startDate));
//in minutes
elapseDuration.asMinutes();
As per documentation about diff
and display duration in minutes

Resources