Date difference issue in moment - javascript

I am trying to create a new Date using 2 dates I have. Basically my new date
Output:
Date 1 = (presentdate +1 month , endDate+1 day, presentdate+1 year);
//Example 1:
var presentDate = "11/12/2018";
var endDate = "2/8/2018";
var Dat1 = "12/9/2018"; //new date
//Example 2 :
var presentDate = "11/12/2018";
var endDate = "5/25/2018";
var Dat1 = "12/26/2018"; //new date
//Example 3 :
var presentDate = "1/5/2018";
var endDate = "5/30/2018";
var Date1 = "2/31/2018"; // invalid date
//should've been 2/28/2018 since that is the last day of the month
//Example 4:
var presentDate = "3/5/2018";
var endDate = "10/30/2018";
var Date1 = "4/31/2018"; //Invalid date. Should've been 4/30/2019 since it's last day of the month
My code:
var mPresent = moment(presentDt);
var mEnd = moment(eDt);
var Date1 = moment({
year: mPresent.year(), // get presentDt's year
month: mPresent.add(1, 'month').month(), // get presentDt's month
date: mStart.date() // get startdt day of the month
});
console.log(Date1);
It doesn't work in all cases because not every month have 30,31 days and then there is the leap year. I need to create a date that is valid because in some of these cases it returns invalid date.
Any help is appreciated. Thank you!

I'm not entirely sure what's going on with your code, but I chopped out most of it and basically did a 1-liner to calculate the # of months difference - seems to work.
document.querySelector("#ok").addEventListener("click", function () {
var paymentDate = document.getElementById("presentDate").value;
var etDate = document.getElementById("endDate").value;
var RemainingPayments = moment(etDate).diff(moment(paymentDate), 'months');
console.log(RemainingPayments);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<label>Present date</label><input id="presentDate" name="presentDate" type="date">
<label>End Date</label> <input id="endDate" name="endDate" type="date">
<button id='ok'>OK</button>

Related

need next month and pre month in js [duplicate]

I read in the documentation of moment.js that if you want to add 1 month to the current date, you can use this code:
var moment = require('moment');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');
But the problem is that this does not add the way I'm expecting it to. For example, let's say the current date is 31/10/2015 (the last day in the month of October). In code:
var currentDate = moment().format('DD-MM-YYYY');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');
console.log(currentDate) // Result --> 31/10/2015
console.log(futureMonth) // Result --> 30/11/2015
If you take a look at the calendar date, 1 month/ 31 days from 31/10/2015 should be 1/12/2015 (the first day of December), not 30/11/2015 (the last day of November).
Could anyone help me fix this problem?
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
DEMO
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
DEMO
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
startDate = "20.03.2020";
var newDate = moment(startDate, "DD-MM-YYYY").add(5, 'days');
console.log(newDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You could try
moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

how to compare a date with system date in javascript

I have to put a validation check that compares the date (ex:12-jun-2015) with the current system date in javascript. I am able to compare the date and year,but since the month is in the 'mon' format, so I am not able to compare with system date.
var date = new Date();
var currentMonth = date.getMonth();
var dateFields = (document.getElementById('startDate1').value.split('-'));
var screenMonth = dateFields[1];
Please suggest
This can be accomplished by using a month array containing all months code in 'mon' format.
var month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var date = new Date();
var currentMonth = date.getMonth();
var dateFields = (document.getElementById('startDate1').value.split('-'));
var screenMonth = dateFields[1];
if(sceenMonth.toLowerCase()==month[currentMonth])
// same month
else
// not same month

Get Diffrence between two date string in momentjs?

I am using momentjs for date and I have one date string, ie,"2015-05-10",I want to get date difference from today
var today= moment().format('YYYY-MM-DD');
How it is possible here?
here is a example,
var now = moment(); // moment object of now
var day = moment("2015-05-13"); // moment object of other date
$scope.difference = now.diff(day, 'days'); // calculate the difference in days
$scope.difference = now.diff(day, 'hours'); // calculate the difference in hours
check more options here
here is a example
You can use diff
//Convert to date
var today = moment();
var date = moment("2015-05-13", "YYYY-MM-DD");
//Use diff
var duration = today.diff(date);
var hours = duration.asHours();
if you are talking about time difference in hours
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

Date function in JS, comparing with a set date not working

I have to pretty much validate and check if the user is underage in ASP. So anyone under the age of 01/07/1998 is underage. I have 3 dropdown lists to select date, month and year. Im using JS. I try using concat and split but they dont work. Can anyone help with this?
function ValidateDate() {
var dDay = document.getElementById('DateList');
var dMonth = document.getElementById('MonthList');
var dYear = document.getElementById('YearList');
var day = dDay.selectedIndex;
var month = dMonth.selectedIndex;
var year = dYear.selectedIndex;
var firstValue = year + month + day;
var setyear = "1998";
var setmonth = "06";
var setdate = "01";
var secondValue = setyear + setmonth + setdate;
var firstDate = new Date();
firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);
var secondDate = new Date();
secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);
if (firstDate > secondDate) {
alert("Pass");
}
else {
alert("Fail");
}
}
<asp:CustomValidator ID="CustomValidatorDate" runat="server"
ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>
First of all your day, month and year variables are reading the index of the drop-downs and not their values.
For instance, you need to use:
var day = dDay.value,
month = dMonth.value,
year = dYear.value;
And then create date object as
var firstDate = new Date(year, month, day);
-Dipen

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Categories

Resources