JavaScript to change Year displayed based on month/day - javascript

I'm trying to create a script that if today's date is before January 16, the current year will print, but if today's date is greater than or equal to January 16, the following year will print.
I am pretty new to coding JavaScript so perhaps I am just missing something stupid. Can anyone help by looking over this code and tell me what I did wrong?
<script type="text/javascript">
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var dd = today.getday();
if (mm < 10) {
mm = '0'+mm
}
var today = new Date("mm/dd")
var other = new Date("01/16")
if (today < other){
var printDate = theDate.getFullYear();
}
else if (today >= other){
var printDate = theDate.getFullYear()+1;
}
</script>
Then in the HTML:
<strong>16 January</strong> <script>document.write(printDate);</script>
Output right now is "undefined." Any ideas would be greatly appreciated!

var today = new Date("mm/dd") // Invalid Date
var other = new Date("01/16") // Tue Jan 16 2001 00:00:00 GMT-0800 (PST)
this should start you on the right process - you need to compare each calendar item (first month, then day) to determine what you are looking for
all the variables you need:
var Today_day = (integer)
var Today_month = (integer)
var Compare_day = (integer) 16 // or 15? not sure about base 0 for a day
var Compare_month = (integer) 0
you know how to get Today_day and Today_month - so you should have everything you need

The simplified condition is: if month is not January (not 0), or date is after the 15th, then get next year:
var today = new Date, year = today.getFullYear();
if (today.getMonth() || today.getDate() > 15) year++;
console.log( year );
Or a bit shorter on one line:
var date = new Date, year = date.getFullYear() + (date.getMonth() || date.getDate() > 15)
console.log( year );

Related

Manipulating Date/time with JS and moment

I have 2 dates and I need to create a 3rd date using those 2 dates.
if (document.getElementById("endDate"))
endDate = document.getElementById("endDate").value;
if (document.getElementById("presentDate"))
presentDate = document.getElementById("presentDate").value;
If Present date = "12/5/2018" and End date = "12/25/2018" then my New date = "12/26/2018";
Since, JavaScript date months range from 0-11 and also the dates are kind of messy, I am not getting the desired results.
What I tried:
var presentDt = new Date(presentDate);
var endDt = new Date(endDate);
var newDay = endDt.getUTCDate()+1;
var presentMonth = presentDt.getUTCMonth();
var presentYear = presentDt.getUTCFullYear();
var nextDate= presentMonth + '/' + endDay + '/' + presentYear;
Issue 1: This above code works but if my endDate is on the 31st, then adding UTCDate+1 makes it 32, which returns invalid date.
Issue 2: If I do UTCMonth(), it returns 11 but if I want to add 2 months then it returns 13 which is also invalid. The issue is basically that I am not able to manipulate the dates as I want.
I also tried moment, however I am having similar issues and I am not able to manipulate the dates easily as I want them to.
Also tried getDate and getMonth but it does the same thing.
Is there a better way of handling the overall date/time with JavaScript?
1: add/subtract days:
new Date(new Date().setDate(new Date().getDay() + 3))
2: add/subtract months:
new Date(new Date().setMonth(new Date().getMonth() + 3))
//your code
var presentDt = new Date(presentDate);
var endDt = new Date(endDate);
var newDay = new Date(new Date().setDate(endDt.getDay() + 2));
var presentMonth = presentDt.getUTCMonth();
var presentYear = presentDt.getUTCFullYear();
Since your input string is not in a format recognized by new Date() across environments, I suggest to use moment(String, String) to parse it.
Then you can use moment(Object), moment's setters (like year(), month() and date()) and format() to get the desired output.
Here a live sample:
var presentDt = "12/5/2018";
var endDt = "12/25/2018";
// Parse your input with momentjs
var mPresent = moment(presentDt, "MM/DD/YYYY");
var mEnd = moment(endDt, "MM/DD/YYYY");
// Create a new momnt object compliant with your needs
var nextDate = moment({
year: mPresent.year(), // get presentDt's year
month: mPresent.month(), // get presentDt's month
date: mEnd.add(1, 'day').date() // get endDt day of the month and add 1 day to it
});
// Display the result in the format you need
console.log(nextDate.format("MM/DD/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note that you will get 01 as day result when endDt represents the last day of the month.
This is what i did:
First i created the following functions to look at the number of days and months.
function formattedDate(date) {
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return (monthIndex + 1) + '/' + day + '/' + year;
}
function myNewDate(datestring) {
var dates = datestring.split("/");
var year, month, day;
if (dates.length < 3) {
dates = datestring.split("-");
year = dates[0];
month = dates[1] - 1;
day = dates[2];
} else {
year = dates[2];
month = dates[0] - 1;
day = dates[1];
}
var days = [31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31];
// Overflow day
if (day > days[month])
day = days[month];
return new Date(year, month, day);
}
function newDate(date1, date2) {
var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var year = date1.getFullYear();
var month = date1.getMonth() + 1;
var day = date2.getDate() + 1;
// Check leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
days[1] = 29;
// Overflow day
if (day > days[month])
day = days[month];
var newdate = new Date(year, month, day);
return newdate;
}
Here, i used the above function to create my new date. You can also add/subtract days/months as you want by updating the above.
var mpresent = myNewDate(presentDate);
var mstart = myNewDate(startDate);
var myDate = (formattedDate(newDate(mpresent, mstart)));

Change particles if is winter in javascript

I have two configurations (json) for particles js. One of them is for winter time, so it should be active from 21. December to 21. March. I tried many things, and still not working (Not because is still November :) )
Last thing I tried is this
var today = new Date();
var tDate = today.getDate();
var tMonth = today.getMonth();
var startingDate = new Date();
var sDate = startingDate.setDate(1);
var sMonth = startingDate.setMonth(10);
var endingDate = new Date();
var eDate = endingDate.setDate(21);
var eMonth = endingDate.setMonth(2);
if (tMonth >= sMonth && tMonth <= eMonth) {
if (tDate >= sDate && tDate <= eDate) {
particlesJS.load('particles', '../../Content/Scripts/particles/particles-config-winter.json');
}
}
else {
particlesJS.load('particles', '../../Content/Scripts/particles/particles-config.json');
}
This does not make sense, because starting and ending date is both 21. I tried to compare as string, didn't work out. I have no ideas how to compare two dates in javascript. Any help?
You could use this function:
function isWinter(dt) {
const m = dt.getMonth();
return m == 11 ? dt.getDate() >= 21 : m == 2 ? dt.getDate() < 21 : m < 2;
}
Call it for today's date like this:
if (isWinter(new Date())) { /*....*/ }
One of the issues in your attempt is that setMonth and setDate methods return the modified date as number of milliseconds (not just a month or day part) and mutate the date on which the method is called.
Explanation of the function:
The ternary expression uses this logic:
If the month is December (11), then return true when the day-of-the-month is at least 21 or false otherwise: this is what dt.getDate() >= 21 evaluates to (true or false).
Otherwise, if the month is March (2), then return true when the day-of-the-month is less than 21 or false otherwise: same principle as above, but reversed
Otherwise, return true when the month comes before March ( < 2 ) and false otherwise: this is what m < 2 evaluates to.
Date manipulation is always a struggle. If you don't mind libraries to handle this for you, i would suggest you to look at MomentJs which makes it easy to manipulate date and time. However each library you add, you add unnecessary code which you might not need. Therefore if you only need do a few date manipulations, it might not be worth it and trincot's's answer is perfect, if you don't really need MomentJs.
Following the line of trincot's answer, this is how you do the same thing in MomentJs:
function isWinter(date){
date.year(moment().year()); //Normalize year.
let winterStart = moment('21-12', 'DD-MM');
let winterEnd = moment('21-03', 'DD-MM');
return !date.isBetween(winterEnd, winterStart, 'day')
}
//Tests:
let today = moment('20-12', 'DD-MM');
alert(isWinter(today)); //false
today = moment('21-12', 'DD-MM');
alert(isWinter(today)); //true
today = moment('21-03', 'DD-MM');
alert(isWinter(today)); //true
today = moment('22-03', 'DD-MM');
alert(isWinter(today)); //false
today = moment('22-03-2019', 'DD-MM-YYYY');
alert(isWinter(today)); //false
today = moment('21-03-2019', 'DD-MM-YYYY');
alert(isWinter(today)); //true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
To explain why your code doesn't work:
var today = new Date();
var tDate = today.getDate();
var tMonth = today.getMonth();
var startingDate = new Date();
// This sets the date to the first of the month, and sets sDate to a number
// that is the time value of the adjusted date
var sDate = startingDate.setDate(1);
// This sets the month to November and sMonth to the adjusted time value
var sMonth = startingDate.setMonth(10);
var endingDate = new Date();
// As above, this sets endingDate to 21 March and sets eDate and eMonth to numbers
var eDate = endingDate.setDate(21);
var eMonth = endingDate.setMonth(2);
// This will never be true after 1970-01-01 as you're comparing a months to a time values
if (tMonth >= sMonth && tMonth <= eMonth) {
if (tDate >= sDate && tDate <= eDate) {
Even if this used correct values, the logic doesn't work as even for a date in the range, you're then comparing the date (day number) when that should only be compared if the month is March or November, not any other month (per Trincot's answer).
It's easier if you create dates for 21 March and 21 December in the current year, then see if the current date falls in the range. If it does, it's not winter. If it doesn't, it's winter. I've assumed that the range is inclusive, adjust the dates if that isn't the case.
function isWinter(date = new Date()) {
var start = new Date(date.getFullYear(), 2, 21);
var end = new Date(date.getFullYear(), 11, 21);
return date > start && date < end;
}
[new Date(2018, 0, 1), // 1 Jan 2018, winter
new Date(2018, 2,21), // 21 Mar 2018, winter
new Date(2018, 5, 1), // 1 Jun 2018, not winter
new Date(2018,11,21), // 21 Dec 2018, winter
new Date() // Today ...
].forEach(d => console.log(`${d} is ${isWinter(d)?'not ':''}winter`));

How can I show the days of last week in javascript?

I need a script that show the days of the last week, until today.
But when it's early in the month, like on day 4, my code has this problem.
I'm using getDate(). Is there a function that can help me?
result
You can use getDate(), but don't put it in a variable that you then just decrement with the risk of going to 0 and below.
Instead use setDate() (potentially in combination with getDate()) to decrement your date object day by day, and then read out the date in the format you want:
var dt = new Date();
headers = ['Hoje'];
for (var i = 1; i < 7; i++) {
dt.setDate(dt.getDate() - 1);
headers.push(dt.toLocaleDateString('pt-PT').substr(0,5));
}
console.log(headers);
To go back a week from today, regardless of where in the month you are (even within seven days from the beginning of the month), just .setDate() to a value that is seven (days) less than what .getDate() gives:
var d = new Date()
d.toDateString()
"Thu May 04 2017"
// go back a week
d.setDate(d.getDate() - 7);
1493321406767
// prove that it worked
d.toDateString()
"Thu Apr 27 2017"
You can use getDay method which gives the day of the week (1-monday, 3-wednesday). From this value you can put a decreasing loop till 1-monday or 0-sunday to show previous day of week.
var weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var d = new Date();
var currDay = d.getDay();
var currDate = d.getDate();
var str = "";
for(var count=currDay; count>=0 && currDate >= 1; count--, currDate--){
str += currDate +" "+weekdays[count] + ", ";
}
console.log(str);
Today's output: 5 Fri, 4 Thu, 3 Wed, 2 Tue, 1 Mon

javascript: get month/year/day from unix timestamp

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}
var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).
Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.

How do I calculate the date in JavaScript three months prior to today?

I Am trying to form a date which is 3 months before the current date. I get the current month by the below code
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
Can you guys provide me the logic to calculate and form a date (an object of the Date data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?
var d = new Date();
d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
var d = new Date("January 14, 2012");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() - 3);
console.log(d.toLocaleDateString());
There are some caveats...
A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
It also says that one month is 30.4167 days long:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
const d = new Date("March 31, 2019");
console.log(d.toLocaleDateString());
const month = d.getMonth();
d.setMonth(d.getMonth() - 1);
while (d.getMonth() === month) {
d.setDate(d.getDate() - 1);
}
console.log(d.toLocaleDateString());
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
I recommend using a library called Moment.js.
It is well tested, works cross browser and on server side(I am using it both in Angular and Node projects). It has great support for locale dates.
http://momentjs.com/
var threeMonthsAgo = moment().subtract(3, 'months');
console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00
.format() returns string representation of date formatted in ISO 8601 format. You can also use it with custom date format like this:.format('dddd, MMMM Do YYYY, h:mm:ss a')
A "one liner" (on many line for easy read)) to be put directly into a variable:
var oneMonthAgo = new Date(
new Date().getFullYear(),
new Date().getMonth() - 1,
new Date().getDate()
);
This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.
function monthAdd(date, month) {
var temp = date;
temp = new Date(date.getFullYear(), date.getMonth(), 1);
temp.setMonth(temp.getMonth() + (month + 1));
temp.setDate(temp.getDate() - 1);
if (date.getDate() < temp.getDate()) {
temp.setDate(date.getDate());
}
return temp;
}
To make things really simple you can use DateJS, a date library for JavaScript:
http://www.datejs.com/
Example code for you:
Date.today().add({ months: -1 });
If the setMonth method offered by gilly3 isn't what you're looking for, consider:
var someDate = new Date(); // add arguments as needed
someDate.setTime(someDate.getTime() - 3*28*24*60*60);
// assumes the definition of "one month" to be "four weeks".
Can be used for any amount of time, just set the right multiples.
I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.
function addMonths(date, months) {
var result = new Date(date),
expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;
result.setMonth(result.getMonth() + months);
if (result.getMonth() !== expectedMonth) {
result.setDate(0);
}
return result;
}
var dt2004_05_31 = new Date("2004-05-31 0:00"),
dt2001_05_31 = new Date("2001-05-31 0:00"),
dt2001_03_31 = new Date("2001-03-31 0:00"),
dt2001_02_28 = new Date("2001-02-28 0:00"),
result = addMonths(dt2001_05_31, -2);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, -3);
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, 36);
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2004_05_31, -38);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
console.log('Done.');
Do this
let currentdate = new Date();
let last3months = new Date(currentdate.setMonth(currentdate.getMonth()-3));
Javascript's setMonth method also takes care of the year. For instance, the above code will return 2020-01-29 if currentDate is set as new Date("2020-01-29")
For get date three monts prior to today :
let d = new Date(new Date().setMonth(new Date().getMonth() - 3))
console.log(d.toISOString().slice(0, 10))
// 2022-05-24 (today is 2022-08-24)
var d = new Date("2013/01/01");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() + 18);
console.log(d.toLocaleDateString());
This is the Smallest and easiest code.
var minDate = new Date();
minDate.setMonth(minDate.getMonth() - 3);
Declare variable which has current date.
then just by using setMonth inbuilt function we can get 3 month back date.
There is an elegant answer already but I find that its hard to read so I made my own function. For my purposes I didn't need a negative result but it wouldn't be hard to modify.
var subtractMonths = function (date1,date2) {
if (date1-date2 <=0) {
return 0;
}
var monthCount = 0;
while (date1 > date2){
monthCount++;
date1.setMonth(date1.getMonth() -1);
}
return monthCount;
}
As I don't seem to see it already suggested....
const d = new Date();
const day = d.getDate();
const goBack = 3;
for (let i = 0; i < goBack; i++) d.setDate(0);
d.setDate(day);
This will give you the date of today's date 3 months ago as .setDate(0) sets the date to the last day of last month irrespective of how many days a month contains. day is used to restore today's date value.
var todayDate = new Date().toISOString().slice(0, 10);
var d = new Date(todayDate);
d.setMonth(d.getMonth() -3);
console.log(todayDate)
console.log(d.toISOString().slice(0, 10));
d.setMonth changed local time in browser try
const calcDate = (m) => {
let date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
let days = 0;
if (m > 0) {
for (let i = 1; i < m; i++) {
month += 1;
if (month > 12) {
year += 1;
month = 1;
}
days += new Date(year, month, 0).getDate();
}
} else {
for (let i = m; i < 0; i++) {
month -= 1;
if (month < 1) {
year -= 1;
month = 12;
}
days -= new Date(year, month, 0).getDate();
}
}
const newTime = date.getTime() + 3600 * 24 * 1000 * days;
return new Date(newTime);
};
calcDate(3)//+3 month
Since "Feb 31th" is auto converted to "March 3" or "March 2", as a month before "March 31th", which is quite counterintuitive, I decided to do it just like how I do it in my mind.
Similar to #Don Kirkby 's answer, I also revise the date with the last day of the target month.
function nMonthsAgo(date, n) {
// get the target year, month, date
const y = date.getFullYear() - Math.trunc(n / 12)
const m = date.getMonth() - n % 12
let d = date.getDate()
if (d > 27) { // get a valid date
const lastDateofMonth = new Date(y, m + 1, 0).getDate()
d = Math.min(d, lastDateofMonth)
}
return new Date(y, m, d)
}
d = new Date('2022-03-31')
nMonthsAgo(d, 1).toLocaleDateString()
Finally, I love what #gilly3 said in his answer:
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
for (let monthOfYear = 0; monthOfYear < 12; monthOfYear++) {
const maxDate = new Date();
const minDate = new Date();
const max = maxDate.setMonth(maxDate.getMonth() - (monthOfYear - 1), 0);
const min = maxDate.setMonth(minDate.getMonth() - (monthOfYear), 1);
console.log('max: ', new Date(max));
console.log('min: ', new Date(min));
}
In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)
dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month
//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month.
Hope to help you dude.
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)
dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month
//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
var date=document.getElementById("date");
var d = new Date();
document.write(d + "<br/>");
d.setMonth(d.getMonth() - 6);
document.write(d);
if(d<date)
document.write("lesser then 6 months");
else
document.write("greater then 6 months");
Pass a JS Date object and an integer of how many months you want to add/subtract. monthsToAdd can be positive or negative. Returns a JS date object.
If your originalDateObject is March 31, and you pass -1 as monthsToAdd, then your output date will be February 28.
If you pass a large number of months, say 36, it will handle the year adjustment properly as well.
const addMonthsToDate = (originalDateObject, monthsToAdd) => {
const originalDay = originalDateObject.getUTCDate();
const originalMonth = originalDateObject.getUTCMonth();
const originalYear = originalDateObject.getUTCFullYear();
const monthDayCountMap = {
"0": 31,
"1": 28,
"2": 31,
"3": 30,
"4": 31,
"5": 30,
"6": 31,
"7": 31,
"8": 30,
"9": 31,
"10": 30,
"11": 31
};
let newMonth;
if (newMonth > -1) {
newMonth = (((originalMonth + monthsToAdd) % 12)).toString();
} else {
const delta = (monthsToAdd * -1) % 12;
newMonth = originalMonth - delta < 0 ? (12+originalMonth) - delta : originalMonth - delta;
}
let newDay;
if (originalDay > monthDayCountMap[newMonth]) {
newDay = monthDayCountMap[newMonth].toString();
} else {
newDay = originalDay.toString();
}
newMonth = (+newMonth + 1).toString();
if (newMonth.length === 1) {
newMonth = '0' + newMonth;
}
if (newDay.length === 1) {
newDay = '0' + newDay;
}
if (monthsToAdd <= 0) {
monthsToAdd -= 11;
}
let newYear = (~~((originalMonth + monthsToAdd) / 12)) + originalYear;
let newTime = originalDateObject.toISOString().slice(10, 24);
const newDateISOString = `${newYear}-${newMonth}-${newDay}${newTime}`;
return new Date(newDateISOString);
};
Following code give me Just Previous Month From Current Month even the date is 31/30 of current date and last month is 30/29/28 days:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date after changing the month.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var d = new Date("March 29, 2017"); // Please Try the result also for "March 31, 2017" Or "March 30, 2017"
var OneMonthBefore =new Date(d);
OneMonthBefore.setMonth(d.getMonth(),0);
if(OneMonthBefore.getDate() < d.getDate() )
{
d.setMonth(d.getMonth(),0);
}else
{
d.setMonth(d.getMonth()-1);
}
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
var d = new Date();
document.write(d + "<br/>");
d.setMonth(d.getMonth() - 6);
document.write(d);

Categories

Resources