need next month and pre month in js [duplicate] - javascript

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')

Related

Date difference issue in moment

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>

How to get Last Day data using Date Object in JavaScript?

I am working to filter data. Filter will be Last Day, Last Week, Last Month.
My code is :
For Last Week :
dateUntil = Date.now();
dateSince = date.setDate(date.getDate()-7)
Last Month :
dateUntil = Date.now();
dateSince = date.setDate(date.getDate()-30)
In Last Day filter I am using :
dateUntil = Date.now();
dateSince = date.setDate(date.getDate()-1);
In last dates it shows, data from this time to yesterday this time. But I want to set Last dates 12.00 am to 11.59pm.
How can I do this ?
You can use below it worked for me :
var d = new Date();
d.setDate(d.getDate()-1);
alert(d);
Hope below code will help you
var datenow = new Date().toDateString();
var dateUntil = new Date(datenow);
var dateSince = new Date(datenow);
dateSince.setDate(dateUntil.getDate()-1);

How can I get last week date starting monday to sunday in javascript

I want a javascript function that gives me start_date as the last week monday date and end_date as last week sunday date.
So for example, today is 03/09/2016, so I want
start_date = 02/29/2016
end_date = 03/06/2016
so far I have wriiten the code as
function GetLastWeekDate(){
start_date = new Date();
start_date.setHours(0,0,0,0);
end_date = new Date();
var date=null;
var curr = date ? new Date(date) : new Date();
var first = curr.getDate() - curr.getDay("monday"),
last = first + 6;
start_date.setDate( first );
end_date. setDate( last );
}
(function() {
var original = Date.prototype.getDay;
var daysOfWeek = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
};
Date.prototype.getDay = function(weekBegins) {
weekBegins = (weekBegins || "sunday").toLowerCase();
return (original.apply(this) + 7 - daysOfWeek[weekBegins]) % 7;
};
})();
but its giving me date as
03/07/2016 and 03/13/2016
how do I fix this to get the dates I want?
If you have a lot of date handling to do, I can only strongly suggest that you use the moment.js library.
In this case, the dates would be :
var startDate = moment().subtract(1, 'week').startOf('week');
var endDate = moment().subtract(1, 'week').endOf('week');
Here you can see it in action :
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("fromDate").textContent = moment().subtract(1, "week").startOf("week");
document.getElementById("toDate").textContent = moment().subtract(1, "week").endOf("week");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<html>
<body>
<p>From : <span id="fromDate"></span></p>
<p>To : <span id="toDate"></span></p>
</body>
</html>
If in case you just want plain js solution w/out any external libraries. You can try this instead.
var dateNow = new Date();
var firstDayOfTheWeek = (dateNow.getDate() - dateNow.getDay()) + 1; // Remove + 1 if sunday is first day of the week.
var lastDayOfTheWeek = firstDayOfTheWeek + 6;
var firstDayOfLastWeek = new Date(dateNow.setDate(firstDayOfTheWeek - 7));
var lastDayOfLastWeek = new Date(dateNow.setDate(lastDayOfTheWeek - 7));
In the above solution, firstDataOfLastWeek will be previous week Monday, and lastDayOfLastWeek will be previous week Sunday.

Comparing datetimes in javascript in format YYYY-MM-DD HH:MM:SS

I have to compare two date times in javascript. The dates I have are of the form
YYYY-MM-DD HH:MM:SS.
I am using the below code for it
var date1 = new Date("2015-08-20 09:38:20");
var date2 = new Date("2015-08-20 08:00:00");
The problem here is that when I use "/" in place of "-", I get the expected results. But when for this format I do
date1 > date
It returns false
Using momentJs is not an option for me and also I am getting the dates from soemewhere so would have to preserve the format. How do I compare the dates of the above given format in javascript
Try this:
var date1 = '2015-08-20 09:38:20';
var date2 = '2015-08-20 08:00:00';
var date1Updated = new Date(date1.replace(/-/g,'/'));
var date2Updated = new Date(date2.replace(/-/g,'/'));
console.log(date1Updated > date2Updated);
I was not able to reproduce the given behavior, but you could try
converting the date1 and date2 variables to miliseconds and storing those in separate vars since Jan 1st 1970.
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
this gives ( for your given example )
1440056300000
1440050400000
and in a comparison
date1_ms > date2_ms
returns true
This is typical of JavaScript dates. All browsers seem to treat date strings differently. My experience is write your own parser if you know the format you want to deal with.
Something like the below will work. Feel free to tidy it up and make it more generic for your own use.
function parseDateString(dateString) {
var dateParts = dateString.split(' ');
var dateOnlyString = dateParts[0];
var timeString = dateParts[1];
var dateOnlyParts = dateOnlyString.split('-');
var year = dateOnlyParts[0];
var month = dateOnlyParts[1] - 1;
var day = dateOnlyParts[2];
var timeParts = timeString.split(':');
var hours = timeParts[0];
var minutes = timeParts[1];
var seconds = timeParts[2];
return new Date(year, month, day, hours, minutes, seconds);
}
jsfiddle for test: http://jsfiddle.net/04nh4q9w/
function getDate(dateString) {
//This function assumes that the dateString will always be of the format YYYY-MM-DD HH:MM:SS
var dateParts = dateString.split(' ');
var dateStr = dateParts[0].split('-');
var timeStr = dateParts[1].split(':');
var dateTimeArr = datestr.concat(timestr)
return new Date(dateTimeArr[0], dateTimeArr[1]-1, dateTimeArr[2], dateTimeArr[3], dateTimeArr[4], dateTimeArr[5]);
}
var date1 = getDate("2015-08-20 09:38:20");
var date2 = getDate("2015-08-20 08:00:00");
date1 > date2 will be true for any browser.
function convertTo24Hour(time) {
time = time.toUpperCase();
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('AM') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('PM') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(AM|PM)/, '');
}

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");

Categories

Resources