Javascript How to increase Month when Date is over today month [duplicate] - javascript

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 1 year ago.
i really stuck at this date. Let say today is 01 20 2021, and i want to add 14 day later to get expired date. so for the expired date should be 02 03 2021, but i only get 01 03 2021. Can anyone help me on this. Thanks
this is my code
var today = new Date();
var monthIndex = today.getMonth()+1;
var year = today.getFullYear();
var addday = new Date(new Date('1.20.2021').getTime()+(14*24*60*60*1000));
var nextDay = addday.getDate();
var nextMonth = monthIndex;
console.log('day',day)
return nextMonth+'.'+nextDay+'.'+year
//the return that I want is 2.03.2021

You didnt update the value for monthIndex. You must use:
var nextMonth = addday.getMonth()+1;

Just use Date.setDate function for this.
// new Date('1.20.2021') => Jan 20 2021
const dateStr = '1.20.2021';
const [mm, dd, yyyy] = dateStr.split('.');
const today = new Date(yyyy, +mm-1, dd);
// add 14 days
const newDate = new Date(new Date(today).setDate(today.getDate() + 14));
console.log(`Today: ${today}`);
console.log(`New Date: ${newDate}`);
console.log(newDate.getMonth() + 1 + '.' + newDate.getDay() + '.' + newDate.getFullYear());

Related

How would I only display the month and day and date with my JS [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 days ago.
I have used js to get the date for the current week displaying the first day of the week (Monday) and the last day of the week (Sunday). This is fine but it displays everything, date, time, timezone, etc. I only want to display the day of the week, the month, and the day's date. I want it to look like Mon Feb 13 and not Mon Feb 13 2023 15:38:09 GMT-0500 (Eastern Standard Time). How would I do it with my current code?
<p class="break"><strong>This class schedule reflects the week <span id="start"></span> - <span id="end"></span></strong></p>
<script type="text/javascript">
const today = new Date();
function getFirstDayOfWeek(d) {
const date = new Date(d);
const day = date.getDay();
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
const firstDay = getFirstDayOfWeek(today);
const lastDay = new Date(firstDay);
lastDay.setDate(lastDay.getDate() + 6);
document.getElementById("start").innerHTML = firstDay;
document.getElementById("end").innerHTML = lastDay;
</script>
I tried to add .getUTCDate() at the end and it didn't work.
Enter your date in new Date(yourdate)
const dateFormat = new Date() .toLocaleString("default", {weekday:"short",month: "short", day: "numeric" });
console.log(dateFormat)

Javascript + 7 days ( Only want dd-mm-yy)

I want to change this date to be formatted to DD-MM-YY
new Date(new Date().setDate(new Date().getDate() + 7)))
Current result: Thu Sep 15 2022 02:16:38 GMT+0200 (Central European Summer Time)
Wanted result: 15-09-22
I suggest solving the problem step by step.
Check the Date object documentation. There are methods that return the day, month, and year.
Add leading "0" when you need it. For instance, like this: ${value < 10 ? '0' : ''}${value}.
Concatenate the strings:
`${dayString}-${monthString}-${date.getFullYear()}`
let date = new Date()
date.setDate(date.getDate() + 7);
const day = date.getDate();
const month = date.getMonth();
const dayString = `${day < 10 ? '0' : ''}${day}`;
const monthString = `${month < 10 ? '0' : ''}${month}`;
const formatted = `${dayString}-${monthString}-${date.getFullYear()}`;
const event = new Date(new Date().setDate(new Date().getDate() + 7));
var day = event.getDate();
var month = event.getMonth();
var year = event.getFullYear();
var date = day + '-' + month + '-' + year;
date.toString();
I did find a fix for my issues no more comments are necessary

new Date can't give me right time

startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = startDate.slice(5,7);
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month, day, hour, minute);
console.log(selEndDatetime);
I want to see "Tue Mar 07 2019 12:00:00 GMT+0900 (한국 표준시)", but console shows me the message "Sun Apr 07 2019 12:00:00 GMT+0900 (한국 표준시)".
What is wrong this code and how can I modify it to get the desired output?
The month starts at 0. You need to parse month from string to integer and minus 1 when creating a date instance.
startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = parseInt(startDate.slice(5,7))
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month - 1, day, hour, minute);
console.log(selEndDatetime);
You can simply pass the startDate string as an argument to the Date in order to create selEndDatetime
Code:
const startDate = '2019-03-07 (목) 12:00';
const selEndDatetime = new Date(startDate);
console.log(selEndDatetime);

Javascript Date Modifiying

I have written these two javascript functions:
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
and
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
The first one should return a new date with the same year/month/day but with a different hour of the day (e.g. switch 2015-04-05 15:00 to 2015-04-05 16:00).
The second one should just return a date-string in the format dd.MM.yyyy.
Now if I call
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
Where hour is a function parameter and for example 15 (tested with alert), in my "dateLabel" it says 05.01.2015. But if I do
alert (selectedDate);
the result is: Sun Apr 05 2015 15:52:26 GMT+0200 (CEST) => now.
selectedDate is not modified between the calls (alert and set the innerHTML).
I think the two functions do not do what I suppose them to, but maybe you find the mistake.
Thank you !
EDIT:
I tried this code:
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
document.getElementById("datumLabel").innerHTML = getDateDescriptionFromDate(startDate); // 05.01.2015
I don't know why you're surprised by what selectedDate is returning. You have only set it to new Date() (now). Nothing in the code is manipulating this variable from the point of creation.
You are, however, manipulating the value and storing the change in startDate and dateLabel.innerHTML. You would only notice the formatting though since the second function strips any change in "time" (done by the first function).
So, in short: You create a date (now), change the time, then format it to only show date.
var selectedDate = new Date();
//selectedDate value = the date and time right now
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
//startDate value = whatever selectedDate was + hours sent as parameter
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
//Formatted value of startDate, to only show date
As per comment:
You're missing that month in javascript is zero-based. So you'll have to do something like:
var month = date.getMonth() + 1; //in the second function
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, 15);
document.getElementById("dateLabel").innerHTML = 'Your current system date: ' + getDateDescriptionFromDate(startDate);
<div id="dateLabel"></div>
If you try this, this should give you save value for your alert and Label, the value you are using for the Label is different than the value you are trying to use alert on.
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
var startDateDesc = getDateDescriptionFromDate(startDate);
alert(startDateDesc) // 05.01.2015
document.getElementById("datumLabel").innerHTML = startDateDesc; // 05.01.2015

How to determine one year from now in Javascript

I'm trying to get one year from now's date, and it's not working.
JS:
var now = new Date();
var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());
var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());
Output:
one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)
one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)
The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.
If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.
Thanks!
This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().
As setYear() is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)
Use this:
var startDate = new Date();
startDate.setFullYear(startDate.getFullYear() - 1);
Using some of the answers on this page and here,
I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:
Date.prototype.addYears = function(n) {
var now = new Date();
return new Date(now.setFullYear(now.getFullYear() + n));
};
console.log('Year from now is', new Date().addYears(1));
In very simple way. use this code.
// define function
function nextYearDate(date1) {
var date2 = new Date(date1);
var date3 = date2.setDate(date2.getDate() - 1);
var date = new Date(date3);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear()+1;
var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
$("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />
<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />

Categories