Adding two different dates using JavaScript [duplicate] - javascript

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Add A Year To Today's Date
(9 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 1 year ago.
Hello guys,
I am trying to do the following:
1- Get the value from the calendar the user picked.
2- Add five years to the value chosen.
3- subtract the Value + five years from the current date.
4 Display the result of (value + 5 years - the current date).
So far that is what I have tried, the result in milliseconds won't be added properly it is kind of adding two strings to each other which I am not looking to do so.
let selectDate = document.getElementById('Calender').value;
let exact = Date.parse(selectDate);
let fiveYearsInMs = "157784760000";
console.log(exact+fiveYearsInMs);
Ps: I am looking to use JavaScript only, no moment.js, or anything else
any help, please?

Here is one method to add 5 years to a date. This method requires the input date to be a recognizable format, such as would come from a date-picker or date field from a database. It converts the incoming string into a date format - after which we rebuild the date string, adding 5 to the years.
let fiveYears =
(d.getFullYear() + 5) + "-" + // we get the year and add 5
("0" + (d.getMonth() + 1)).slice(-2) +"-"+ // we get the month (which is zero based so we need to add 1 - then we pad it with a leading zero and finally take the last 2 via slice()
("0" + d.getDate()).slice(-2); // we get the day and pad as mentioned above
document.querySelector('input').addEventListener('change', (e) => {
doDate(e.target.value)
})
// this next function relies on the selectDate being a recognizable date format, which it definitely will be if it comes from a date text element like this example
const doDate = (selectDate) => {
//let selectDate = document.getElementById('Calender').value;
let d = new Date(selectDate)
let fiveYears =
(d.getFullYear() + 5) + "-" +
("0" + (d.getMonth() + 1)).slice(-2) +"-"+
("0" + d.getDate()).slice(-2);
console.log(fiveYears) // date string
console.log(new Date(fiveYears)) // date Object
console.log(new Date(fiveYears).getTime()); //milliseconds
}
// Archived: the following line (commented out) is not a reliable way to get the date, even though it will work for most modern browsers today, it's platform and browser dependent.
// I am leaving it here for posterity since this is how the answer was accepted
// let fiveYears = selectDate.split("-").map((e, i) => i == 0 ? +e + 5 : e).join("/");
<input type='date' />

You are close! But just have fiveYearsInMs as an integer, not a string.
let selectDate = "2021-06-13"
let exact = Date.parse(selectDate);
let fiveYearsInMs = 157784760000;
console.log(exact + fiveYearsInMs);
let futureDate = new Date(exact + fiveYearsInMs)
console.log(futureDate)

Related

Javascript logic to find the date based on the given number that is before or after excluding weekends [duplicate]

This question already has answers here:
add/subtract business days in Javascript
(6 answers)
Closed 2 years ago.
I have a strange requirement where I need a find the date based on given number and type = before/after parameter
i.e., for example
Date = new Date() - 3/8/2020 (It can be any date)
type = before
days = 7(It can be any number)
Now I need to find the date excluding the weekends.
In this case it would be 23/7/2020 .Because 2/8,1/8,26/7,25/7 are weekends, so those should be excluded and calculated.
Simillarly if type = after , date will be 12/8/2020 .In this case 8/8 and 9/8 are weekends and those will be excluded.
So how can we implement this as function that takes date,days,type as parameters and return the date.
i.e.,
function calculateDate(day,days,type){
/* Some logic
if(new Date(day).getDay() !== 6||7){};
*/
return date
}
Note : I cant use any libraries like moment/dayjs etc as I have restrictions with the development tool Im using..I need to implement in pure javascript logic
Can any javascript datetime expert help me on this as I couldn't crack this.
Thanks in advance
const date = new Date()
let days = 7 // Adjust accordingly
let delta = -1 // Set +1 to check 'days after' instead of 'days before'
while (days > 0) {
// Remove a day
date = date.setDate(date.getDate() + delta)
// Check if weekend (adjust your days number according to your needs)
const isWeekend = date.getDay() === 6 || date.getDay() === 0
// If it is not a weekend, reduce the number of days to subtract
if (!isWeekend) {
days = days - 1
}
}
return date

javascript - add days to date and date format not working [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 6 years ago.
I've a form with fields .daysfromtoday and #datefromtoday.
I would like to enter a number of days in .daysfromtoday and update #datefromtoday with the date yyyy-mm-dd format. (I know that there are other posts about this subject, but, if possible, I would like someone helps me with code I've written, to learn more)
HTML:
<input type="text" class="daysfromtoday" />
<input type="text" id="datefromtoday" name="delay" />
javascript:
$(document).ready(function (){
$(".daysfromtoday").on('change', function(){//
var waitdays = $( ".daysfromtoday" ).val(); //take value from field .daysfromtoday
var enddate = new Date();
enddate.setDate(enddate.getDate() + waitdays);
var yyyy = enddate.getFullYear().toString();
var mm = (enddate.getMonth()+1).toString();
var dd = enddate.getDate().toString();
document.getElementById("datefromtoday").value = yyyy + '-' + mm + '-' + dd; //outuput
});
});
Problems: (and solutions)
I get weird results: today is 2016-02-26, if I enter 100, I get 2087-7-17
The result format should have the 0 (zeros): 2016-03-08
You probably add string instead of number to the date. Try using parseInt function:
...
enddate.setDate(enddate.getDate() + parseInt(waitdays, 10));
...

JavaScript - toDateString()

Image link is a code that increments the current date by 12 months.
Although I am getting the new date increased by 12 months but when I convert the new date to string by using toDateString() I don't get the output.
Please help me smart JavaScript people :)
Use this function. At least this is the way i give format to my dates in my apps. By the way this is the way stack comunity is telling you to put your code in your question.
function getFormattedDate(date) {
var aux = new Date(parseInt(date.substr(6)));
var year = aux.getFullYear();
var month = (1 + aux.getMonth()).toString();
var day = aux.getDate().toString();
return day + '-' + month + '-' + year;
}
Hope this helps!

pre-populating date input field with Javascript

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
Thanks.
It must be set in ISO-format.
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
http://jsfiddle.net/GZ46K/
Why Not to Use toISOString()
The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
Populate HTML5 Date Input from Date Object w/o Time Zone Change
The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):
let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
Thank you j08691. That link was the answer.
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
You MUST have 4 digits for the year.
You MUST have a dash and no spaces.
You MUST have 2 digits for day and month.
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
Here is an answer based on Robin Drexlers but in local time.
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
This below code populates the local date . The accepted answer populates UTC date.
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
There's an easier way to zero pad than all of the juggling that everyone is doing here.
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
waves to future people

Subtracting date from an input field

I would like to have an input field with a button next to it.
On the input field I will enter a date like this:
2011-07-08
And when I hit the button it should read the time that has been entered on the input field and subtract it with 3 months and one day.
Is this possible?
Thanks in advance
Yes. First you read the date and you convert to a date object
var dateString = document.getElementById('id of your field').value,
date = new Date(dateString);
then you subtract 91 days and output the result
date.setDate(date.getDate() - 91);
alert(date.toString());
Here I assume for simplicity that you actually want 91 days and not 3 months and one day. If you want three months and one day you will do
date.setMonth(date.getMonth() - 3);
date.setDate(date.getDate() - 1);
alert(date.toString());
The Date object will take care of overflows, leap years and everything.
If you want to write it to same field, taking care of zeroes, you can do
function assureTwoDigits(number) {
if (number > 9) {
return '-' + number;
}
else {
return '-0' + number;
}
}
and change the last line to
document.getElementById('id of your field').value = date.getFullYear() + assureToDigits(date.getMonth()) + assureTwoDigits(date.getDate());
You can use Date objects (see here):
extract year, moth and day from the string (using a regular expression or splitting by '-')
buid a new Date object with that data
subtract the date interval
build the string back
The simplest way would be to split it into an array, then use a couple of if/else statements:
var date = (whatever you're pulling the date in as).split('-');
if (date[1] > 3)
date[1] = date[1] - 3;
else
date[0] = date[0] - 1;
var dateOverflow = date[1]-3;
date[1] = 12 - dateOverflow;
And then the same for the days.
Yes, it's possible and it's the most clean if you can do it without some arcane regex magic. Start by converting the date to a Date object:
// this will get you a date object from the string:
var myDate = new Date("2011-07-08");
// subtract 3 months and 1 day
myDate.setMonth(myDate.getMonth()-3);
myDate.setDay(myDate.getMonth(), myDate.getDay()-1);
// And now you have the day and it will be correct according to the number of days in a month etc
alert(myDate);

Categories

Resources