Round Date up or down using Moment - javascript

I am using Moment to compare two datetime values. Specifically using Moment.isSameOrBefore. My two date values are off by milliseconds.
I would like these two values to evaluate as the same:
var date1 = '2019-07-09T15:30:05.8670088'
var date2 = '2019-07-09T15:30:06.3400766'
if (moment(date1).isSameOrBefore(date2, 'second')) {
//do something
}
Is there a way to round, so the datetime values equal so evaluation is true? Or another way to achieve this?

It evaluates as true:
var date1 = '2019-07-09T15:30:05.8670088'
var date2 = '2019-07-09T15:30:06.3400766'
var test = moment(date1).isSameOrBefore(date2, 'second');
console.log(test);
<script src="//unpkg.com/moment"></script>

Related

Moment js. Comparison two dates

How to compare two dates with moment js. I used diff() method , but not worked. How I solve it ?
let lastMessageMinute = moment("06-30-2022").format("HH:mm");
let currentTime = moment(new Date()).format("HH:mm");
const differenceOfTimes = currentTime.diff(lastMessageMinute, "hours");
Convert both dates (before formatting) to milliseconds and compare them. Like
if(lastMessageMinute.valueOf() === currentTime.valueOf())
you need to do like moment().diff()
Your syntax -> moment().format().diff() this is not accept by moment js.
For Example,
var a = moment("18.05.2022", "DD.MM.YYYY");
var b = moment(new Date(), "DD.MM.YYYY");
console.log("diff", b.diff(a, 'hours'));

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>

Time if statement not working

Hi I have a simple if statement which compares to dates, however its not running, I have tried debugging it but doesn't work.
dateFormat = "01/05/2099"
dateMissing = "25/11/2016"
if(dateFormat > dateMissing){
dateFormat = dateMissing;
}
You're comparing strings. That compares their characters, one by one from left-to-right, until it finds a difference, and then uses that difference as the result. Since "2" is > "0", that string is greater than the other.
You need to parse the dates and compare the result. Do not just use new Date(dateFormat) or similar, those strings are not in a format that is handled by JavaScript's Date object. Do the parsing yourself (directly, or via a library). E.g.
var dateFormat = "01/05/2099";
var dateMissing = "25/11/2016";
var parts, dt1, dt2;
var parts = dateFormat.split("/");
var dt1 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
parts = dateMissing.split("/");
var dt2 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
if (dt1 > dt2) {
dateFormat = dateMissing;
}
console.log("dateFormat:", dateFormat);
console.log("dt1", dt1.toString());
console.log("dt2", dt2.toString());
Your can't simply compare the strings containing dates. First, convert them to an acceptable format (milliseconds).
var dateFormat = new Date("05/01/2099").getTime();
var dateMissing = new Date("11/25/2016").getTime();
Then you can do your date comparision.

NaN javascript error when calculating between dates with timestamp

I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}
Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));
The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);
You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);
for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?

Date validation failing

I wish to check whether a one given date is less than the other date using JavaScript + jQuery.
However, when checking a date that is one day less than the given date, the condition is not met.
This is my code;
$('#payment_date').change(function(){
payment_date_1 = String($("#payment_date").val());
s_date_1 = String($("#s_date").text());
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date<s_date){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
ex: when s_date == '2013-07-02' and payment_date == '2013-07-01' the condition is returning false rather than true.
My HTML:
<span style="display:none;" id="s_date">2013-07-02</span>
<input type="text" value="" name="payment_data_info[payment_date]" id="payment_date" class="hasDatepicker" readonly="readonly">
Note; I have checked if both dates are valid, two dates are returning valid dates and the condition is working perfectly well for other instances
I just found out why; I'm using jQuery's date picker. Dates less than and equal to 2013-07-10 returns a valid date and dates less than 2013-07-10 and larger than 2013-06-30 returns an invalid date. Any idea why?
First of all check if variable declaration is the problem, than check if the string parsing returns the dates you're expecting. Maybe s_date and payment_date are invalid after all?
I expierenced difficulties too with the direct comparison (don't know why), so I used the valueOf-function to get values for comparison.
Sure it works ;)
http://jsfiddle.net/4MQkK/
payment_date_1 = "2013-07-01";
s_date_1 = "2013-07-02";
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date < s_date){
alert(payment_date + "is lower than " + s_date);
}
Check your values of payment_date_1 and s_date_1 at least one of them could not be parsed correctly
Try this , I hope it will help.
$('#payment_date').change(function(){
var payment_date_1 = $("#payment_date").val(); //add var
var s_date_1 = $("#s_date").text(); //add var
var payment_date = new Date(payment_date_1);
var s_date = new Date(s_date_1);
if((payment_date.valueOf())<(s_date.valueOf())){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
2 Possible Causes:
1) Where Date is called as a constructor with more than one argument,
if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new Date(2014,1,1),
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
your date format is 'dd/MM/yyyy' but new Date () use format yyyy/dd/mm so 2013-06-30: 30 is month i.e. 30 month more then 06/01/2013 --> 06/06/2015
you need to change the format. for example:
var myDate = "2013/01/30"
var split= myDate .split("/");
new Date (split[2],split[1],split[0]);
2) months in Date() in javascript they numeric 0-11. so 01/03/2013 changed to 01/04/2013
int month = myMonth -1; // for example: mymonth = 'March' => month = 2
can use new Date(2013,month,30);
You can do something like this.
var payment_date_1 = $("#payment_date").val();
var s_date_1 = $("#s_date").text(); or $("#s_date").val();
// IF s_date_1 is a input field then you have to use .val()
For typecast String. You can do
var payment_date_1 = $("#payment_date").val().toString();
var s_date_1 = $("#s_date").val().toString();
PLease create date objects and then check
var first = new Date($("#s_date").text());
var second = new Date($("#s_date_1").text());
if(first.getTime() < second.getTime()) {
// code
}

Categories

Resources