JavaScript struggling with date format [duplicate] - javascript

This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Closed 5 years ago.
I am trying to retrieve a date but I am struggling with the month because January = 0 instead of 1. I need to retrieve items which occured after today -60 days.
var today = new Date();
if (today.getMonth() < 1) {
var numberOfDaysLastMonth = getDaysInMonth(12,today.getFullYear()-1); //number of days in december last year
var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1,today.getFullYear()); //number of days this month
} else {
var numberOfDaysLastMonth = getDaysInMonth(today.getMonth(), today.getFullYear()); //number of days last month
var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1, today.getFullYear()); //number of days this month
};
var startDate = new Date();
var myMonth;
var myYear;
if (today.getMonth() < 1) {
myMonth = today.getMonth() + 1;
myYear = today.getFullYear()-1;
} else {
myMonth = startDate.getMonth()-1;
myYear = today.getFullYear();
};
startDate = myYear+"-"+myMonth+"-"+startDate.getDate(); // returns last month
Is there a more simple (and working) way to do this?

If it's difficult to use dates as they are in Javascript, then modify them to work as they want them to work. An example:
Date.prototype.getMyMonth = function() {return this.getMonth() + 1;};
Now, you can change your code to use .getMyMonth instead of .getMonth.

Related

I am Working on Javascript Dates, i am stuck with adding 7 days to a date [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
console.log(firstDay)
I am Working on Javascript Dates, i am stuck with adding 7 days to this date
Thanks in advance
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
var resultDate = new Date();
resultDate.setDate(first_date.getDate() + 7);
var resultDay = resultDate.toJSON().substring(0, 10);
console.log("First day: " + firstDay)
console.log("7 days from specific day: " + resultDay)

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

JavaScript - Trying to set tomorrow's date using the code below [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
var today = new Date();
var tomorrow = today.setDate(today.getDate() + 1)
console.log(tomorrow)
1596607917318
I am getting 13 digit number after using setDate(). How can I get the date in 2 digit format?
Date outputs in JS often need some manual processing to be exactly what you want. Try this:
// Create new Date instance
var today = new Date();
var tomorrow = today;
// Add a day
tomorrow.setDate(tomorrow.getDate() + 1)
console.log(formatDateToString(tomorrow));
function formatDateToString(date) {
var dd = (date.getDate() < 10 ? '0' : '')
+ date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '')
+ (date.getMonth() + 1);
return dd + "/" + MM;
}
The Date object has different methods that you can use to get certain parts of the timestamp.
// for day-month (i.e.: Oct 31 is 31-10
let formatted = `${tomorrow.getDate()}-${tomorrow.getMonth() + 1}`
See more: https://www.w3schools.com/js/js_date_formats.asp
setDate has changed the date of today.
Therefore output today and don't assign what's returned by setDate.
var today = new Date();
today.setDate(today.getDate() + 1);
console.log(today.toLocaleDateString());
Month is zero based so getMonth() + 1 returns this month, getDate() + 1 returns tomorrow.
var fecha = new Date();
var year = fecha.getFullYear();
var mes = fecha.getMonth() + 1;
var dia = fecha.getDate() + 1;
var hora = fecha.getHours();
var minutos = fecha.getMinutes();
var segundos = fecha.getSeconds();
var output = `Date: ${dia}/${mes}/${year}`+ '\n' + `Time: ${hora}:${minutos}:${segundos}`;
console.log(output)
Nice question, I recently had to do something similar in VB. Here is a simple javascript version, based on your code:
//this gets the date today
var today = new Date();
//we add one, to get the date tomorrow
var tomorrow = today.getDate() + 1
//if tomorrow is a single digit number, we just pad it with a zero
if (tomorrow < 10)
{
tomorrow = '0' + tomorrow
}
//write to the console
console.log(tomorrow)

Adding Day to Date [duplicate]

This question already has answers here:
How to add number of days to today's date? [duplicate]
(16 answers)
Closed 5 years ago.
I have an example below of code that getting the date and adding certain days.
But the result I got from log is like these 1507824000000.
var endDate = new Date('10/03/2017');
var numOfDays = 10;
console.log(endDate.setDate(endDate.getDate() + numOfDays ));
If you want something to see your 10 days added, you can try the following :
var endDate = new Date('10/03/2017');
var numOfDays = 10;
endDate.setDate(endDate.getDate() + numOfDays);
var dd = endDate.getDate();
var mm = endDate.getMonth() + 1;
var y = endDate.getFullYear();
var yourNewDate = dd + '/'+ mm + '/'+ y;
console.log(yourNewDate)

Change date format (Javascript)

I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"

Categories