Comparing two times in MomentJS in the format HH:mm? - javascript

Here I need to compare two times and have to check whether the current time is sameOrBefore the given time.
var workingDayTime = '1900'
var currentTime = moment().format("HH:mm")
var endTime = moment(workingDayTime,"HHmm").format("HH:mm")
console.log(currentTime) // 08:21
console.log(endTime) // 19:00
Assume the value of workingDayTime is coming from API in the format of ``HHMM`. I have checked the moment docs. And used something like endTime.isSameOrAfter(currentTime).
But it is returning endTime.isSameOrAfter is not a function . I believe this is because the current time and endTime have formatted to string this is not a function anymore. Is there any way to achieve the functionality I am looking for. Please help me with your suggestion and feedback

Compare the moment objects without the string formatting:
const workingDayTime = '1900'
const currentMoment = moment()
const currentTime = currentMoment.format('HH:mm')
const endMoment = moment(workingDayTime,"HHmm")
const endTime = endMoment.format("HH:mm")
const msg = (endMoment.isSameOrAfter(currentMoment))
? 'after'
: 'before'
console.log(`${endTime} is ${msg} ${currentTime}`)

Don't format dates before you compare them
import moment from "moment";
var workingDayTime = '1900'
var currentTime = moment()
var endTime = moment(workingDayTime,"HHmm")
console.log(endTime.isSameOrAfter(currentTime)) // true

Related

Time changes after toLocaleTimeString()

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.
Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

How to check if the time is in between given range using moment.js?

I am using moment.js library for time.
I want to check if the time I am getting from the backend is in between 8AM to Noon (12PM). I want to store all the objects whose time is in between 8AM to 12PM.
I am getting date in this format - "2022-04-04T21:43:59Z". I want to use timezone"America/Detroit".
Here is what I have tried but this didn't work;
//this code is inside forEach loop
moment.tz.setDefault($scope.userData.account.timeZone);
var format = 'hh:mm:ss'
var time = moment(response.date,format),
beforeTime = moment('08:00:00', format),
afterTime = moment('11:59:59', format);
if (time.isBetween(beforeTime, afterTime)) {
console.log('is between')
} else {
console.log('is not between')
}
In the output I am getting is not between for all the data but in real there is some data which is having date and time falling under 8am - 12pm.
Is there anything wrong because of timezone?
The reason why your compare isn't working it's because it's not only using time but also the date.
You should first extrapolate the time from the input datetime and use that data to make the comparison like this:
let datetime = moment('2022-04-04T10:00:00Z', 'YYYY-MM-DDTHH:mm:ssZ');
moment({
hour:datetime.hour(),
minute:datetime.minute(),
second:datetime.second()
}).isBetween(beforeTime, afterTime);
//returns bool true or false
That's because all those 3 datetimes will lay in the same solar day and only time will be relevant to the comparison.
Plus you incorrectly dealt with formats when parsing both your input datetimes and times used for before and after.
This is a working solution showing the concept:
//those are the formats your input uses for datetimes and times
const datetime_format = 'YYYY-MM-DDTHH:mm:ssZ';
const time_format = 'HH:mm:ss';
//this is your input crafted as objects having the prop date
var response_timeYESInBetween = {date : "2022-04-04T10:00:00Z"};
var response_timeNOTInBetween = {date : "2022-04-04T21:43:59Z"};
//moment.tz.setDefault($scope.userData.account.timeZone);
//this is where you parse those timestamp strings as moment datetime
var datetime_YESInBetween = moment(response_timeYESInBetween.date, datetime_format);
var datetime_NOTInBetween = moment(response_timeNOTInBetween.date, datetime_format);
//this is where those moment datetime get used to create new datetimes holding those same time but laying on today instead of their original dates
var timeonly_YESinBetween = moment({hour:datetime_YESInBetween.hour(), minute:datetime_YESInBetween.minute(), second:datetime_YESInBetween.second()});
var timeonly_NOTinBetween = moment({hour:datetime_NOTInBetween.hour(), minute:datetime_NOTInBetween.minute(), second:datetime_NOTInBetween.second()});
//this is where we create datetimes (ignoring to pass the date, sets them at today)
var beforeTime = moment('08:00:00', time_format);
var afterTime = moment('11:59:59', time_format);
//we make the comparison to know which times are between beforeTime and afterTime
//note: now all those datetimes are all in the same day and only time will affect the comparison result
var firstComparison = timeonly_YESinBetween.isBetween(beforeTime, afterTime);
var secondComparison = timeonly_NOTinBetween.isBetween(beforeTime, afterTime)
console.log( firstComparison );
//outputs: true
console.log( secondComparison );
//outputs: false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
And if we wanted to better factor the parts:
console.log( isBetween('2022-04-04T10:00:00Z', '08:00:00', '11:59:59') );
//true
console.log( isBetween('2022-04-04T21:43:59Z', '08:00:00', '11:59:59') );
//false
function isBetween(datetime, before, after){
const datetime_format = 'YYYY-MM-DDTHH:mm:ssZ';
const time_format = 'HH:mm:ss';
let originalDatetime = moment(datetime, datetime_format);
let transformed = moment({hour:originalDatetime.hour(), minute:originalDatetime.minute(), second:originalDatetime.second()});
var beforeTime = moment(before, time_format);
var afterTime = moment(after, time_format);
return transformed.isBetween(beforeTime, afterTime);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

Javascript Moment Time add Time Calculation wrong

I am using Moment library in Javascript
I would like to add time, so I tried:
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = time1.add(time2);
let format = moment.utc(add).format("HH:mm:ss")
console.log(format);
I will expected my format will be 10:03:15 but turns out it gave me 18:03:15
I wonder why it add another 8 hours for me, well considered as .utc problem, I try to perform without .utc as follows:
let format = moment(add).format("HH:mm:ss")
It return 02:03:15.
It kinda frustrated I dunno what is happening
*By the way
var add1 = time3.add(5588280, 'ms');
*it works fine by adding with h, m, s, ms to it
Ciao, with moment add you could add time in 3 ways:
moment().add(Number, String);
moment().add(Duration);
moment().add(Object);
This is the version moment().add(Number, String);
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = moment(time1).add(time2.minutes(), "minutes").add(time2.seconds(), "seconds");
let format = add.format("HH:mm:ss");
console.log(format); // without utc
let formatUtc = moment.utc(add).format("HH:mm:ss");
console.log(formatUtc); // with utc
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
This is the version moment().add(Object);
var time1 = moment("10:00:00", "HH:mm:ss");
var time2 = moment("00:03:15", "HH:mm:ss");
var add = moment(time1).add({minutes: time2.minutes()}).add({seconds: time2.seconds()});
let format = add.format("HH:mm:ss");
console.log(format); // without utc
let formatUtc = moment.utc(add).format("HH:mm:ss");
console.log(formatUtc); // with utc
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
You already know the third version :)
add is the two-argument function with the need first argument as the number and second argument is number type in time laps.
i.e it is working with microseconds
time3.add(5588280, 'ms')
Here you can do for your problem
const time1 = moment("10:00:00", "HH:mm:ss");
const time2 = moment("00:03:15", "HH:mm:ss");
// get hours from time2 and add in time1
const add = time1.add(time2.format('mm'), 'hours')
// add minutes using chain
.add(time2.format('mm'), 'minutes')
// add seconds using add method from moment
.add(time2.format('ss'), 'seconds');
const format = moment(add).format("HH:mm:ss")
By using UTC on the moment it converts time into UTC and format make it as
time string format
moment(add).format("HH:mm:ss")
// Your required time:- 13:03:15
moment.utc(add).format("HH:mm:ss")
// required time in UTC:- 07:33:15
You can simply use moment duration function to add two times together we do not use to use extra lines code (like minutes, seconds, or hours) here to get the results you want.
Just add two times with duration and get them as milliseconds and then format them as you like to.
Live Demo:
let time1 = "10:00:00"; //string
let time2 = "00:03:15"; //string
let addTwoTimes = moment.duration(time1).add(moment.duration(time2)) //add two times
let format = moment.utc(addTwoTimes.as('milliseconds')).format("HH:mm:ss") //format
console.log(format); //10:03:15
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>

How to combine date and time into a single datetime object?

In my react native app i need to combine my date and time in to single datetime object. I used react native modal date time picker npm package for get date and time.
I have a datepicker returning a date string, and a timepicker returning a time string. When i try to combine it will give me a output as Invalid date.
concatDateTime = () => {
var date = this.state.date;
var time = this.state.currentTime;
var dateTime = Moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');
console.log(dateTime.format('YYYY-MM-DD HH:mm'));
}
I need dateobject in ('YYYY-MM-DDTHH:mm:s') format.
You can specify the format of your input string to let moment know how to parse it.
var date = '2019-02-16';
var time = '8:24 PM';
// tell moment how to parse the input string
var momentObj = moment(date + time, 'YYYY-MM-DDLT');
// conversion
var dateTime = momentObj.format('YYYY-MM-DDTHH:mm:s');
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Just click on below link,
https://stackblitz.com/edit/typescript-bmgx2p?file=index.ts
I hope it will solve your problem.
Another alternative:
let mDate = moment(data.StartDateLocal).tz("Australia/Melbourne");
let mTime = moment(data.StartTimeLocal).tz("Australia/Melbourne");
let x1 = {
'hour': mTime.get('hour'),
'minute': mTime.get('minute'),
'second': mTime.get('second')
}
mDate.set(x1);
this._json.header.transactionStartDateTime = mDate.format("YYYY-MM-DDTHH:mm:ss");

Categories

Resources