How to tell if string time-A is before time-B? - javascript

if I have 4 variables
startTime;
endTime;
startMerid;
endMerid;
startMarid and endMarid are either going to be 'AM' or 'PM'.
but startTime and endTime are going to be strings like 'dd:dd'
so it may be start:12:30 PM and end:5:30 PM
How can I validate that the end time is not before the start time?
Thanks!!

You can use DateJS:
Date.parse('12:30pm') < Date.parse('5:30pm'); // true
EDIT:
Justin has a good point below. You can find the latest en-US version here
You can find the others in /trunk/build
EDIT 2016:
For those hitting this post in 2016+, it looks like a more up to date repo for DateJS is now at GitHub: https://github.com/datejs/Datejs
Also, it seems MomentJS is a very popular choice these days.

Parse out the hours and minutes fields so you have two separate variables. Then add 12 to hours if it is PM, unless the hour value is already 12. You can then compare the values directly:
if (startTimeHrs * 60 + startTimeMins) >
( endTimeHrs * 60 + endTimeMins){ ... }

Related

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 convert minutes to hours using moment.js

Can anyone tell me how to convert minutes to hours using moment.js and display in hh:mm A format.
For example,
If minutes is 480 it should display output as 08:00 AM.
If minutes is 1080 it should display output as 06:00 PM
Assuming that you always want to add minutes from midnight, the easiest thing to do is:
moment.utc().startOf('day').add(480, 'minutes').format('hh:mm A')
The use of UTC avoids issues with daylight saving time transitions that would cause the time to vary based on the day in question.
If you actually want the number of minutes after midnight on a given day, including the DST transitions take out the utc and just use:
moment().startOf('day').add(480, 'minutes').format('hh:mm A')
Note that the accepted answer has potential issues with DST transitions. For instance if you are in a part of the United States that observes DST:
moment('2016-03-13').hours(2).minutes(30).format('hh:mm A')
"03:30 AM"
The result is not as expected, and will vary between going back and hour or going forward an hour depending on the browser.
Edit: Original answer has been updated to fix bug. As an additional comment, I would be extremely leery of any code that attempts to map a number of minutes to civil time. The bottom line is that 480 minutes into the day is not always 8:00 AM. Consider this in the context of your problem. DST bugs are likely right now.
You can just do the basic arithmetic like so:
function getTimeFromMins(mins) {
// do not include the first validation check if you want, for example,
// getTimeFromMins(1530) to equal getTimeFromMins(90) (i.e. mins rollover)
if (mins >= 24 * 60 || mins < 0) {
throw new RangeError("Valid input should be greater than or equal to 0 and less than 1440.");
}
var h = mins / 60 | 0,
m = mins % 60 | 0;
return moment.utc().hours(h).minutes(m).format("hh:mm A");
}
getTimeFromMins(480); // returns "08:00 AM"
getTimeFromMins(520); // returns "08:40 AM"
getTimeFromMins(1080); // returns "06:00 PM"

Subtract time in 24 hour format using javascript or jquery

I have a start and end time in the format of HH:MM and I need to get the total time in hours. I have tried a couple methods like trimming the string to an hour and minutes then multiplying the hours by 60 and adding the minutes but since the minute string is two digits, 00 I get an answer that is a power of ten greater than what I need. I also feel like this approach is inefficient.
So what is the best way to subtract 04:30 and 22:00? I also have access to moment.js if that is helpful.
Using moment.js' difference
var a = moment('22:00', 'HH:mm');
var b = moment('04:30', 'HH:mm');
a.diff(b, 'hours', true)

Dates in javascript

I need some help with javascript dates. I have found a bug when I was working. I think that it has been solved but I don't know why.
We have a custom calendar with seven days each pages (monday-sunday).
When you pick next (>) it add 7 days. The trouble was that in october 2015 (19-25) when you pressed next, it becomes a new week with days between 25-31 instead of 26-1 week.
This was the code that sum one week:
date = new Date( date.getTime() + num * 86400000 );`
And this is how I "fix" it:
date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + num);`
Now the picker is working, I suppose 86400000 are the milliseconds in a day but why it doesn't work for some days?
Thanks
Late October in your locale is when Daylight Savings or "Summer" time ends. One of the days in that week is slightly shorter than other days.
The internals of the JavaScript runtime know about that, so adding days via the setDate() API gets the right answer.
If I may make a recommendation: check out Moment.js. While it doesn't directly answer your question as to why you're encountering your issue (#Pointy's answer is right), it will make such calculations such as yours much simpler.
Instead of this:
date = new Date( date.getTime() + num * 86400000 );
You can do this:
date = moment().add(1, 'w').toDate()
...and I believe it will account for daylight savings time.

Getting result from moment.js diff/from/fromNow in weeks instead of days

Given this code:
var now = moment();
now.day("Tuesday");
var displayed_week_day = moment();
var one_week = moment.duration(1, 'weeks');
displayed_week_day.day("Tuesday");
displayed_week_day.add(one_week);
console.log(displayed_week_day.from(now));
displayed_week_day.add(one_week);
console.log(displayed_week_day.from(now));
The output is:
in 7 days
in 14 days
The docs would lead me to believe that this would output as "in 1 week" or "in 2 weeks". I don't see a way to pass an argument to this to make it do that.
There was an earlier stack question here: How to get duration in weeks with Moment.js? but this response is quite old and does not seem to apply to current versions of moment.js. Does anyone have thoughts on how to change the output format of this?
Actually, in the docs it says that anywhere from 22 hours to 25 days is represented in terms of days. (>=22 && < 36 hours rounds to a single day, >= 36 hours rounds to 2 days)
See the chart under the Time from now section.
The ability to customized these ranges has been requested and is an open issue here.

Categories

Resources