How To Make A Default Text Display For This Script? - javascript

I'm using a script to display the current date to someone, but I want to do two things to it.
First, I want to change the format to MM/DD/YY, so it's only showing the year in 2 digits.
Then second, how can I add a default? So if it's not able to be pulled by someone, it will show "Today" instead of a date?
Here's the script if anyone could help:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)

Working FIDDLE Demo
Add a div to your HTML and put your default text inside it:
<div id="date">Today</div>
Then with javascript, change it, and if the user don't have javascript, it remains not changed:
// create date
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + "/" + day + "/" + (year + '').substring(2);
// now insert it
document.getElementById('date').innerHTML = date;
[!] Don't forget to add the JS after your element or add it to document ready.

I don't see any reason for this to fail, If javascript is enabled in the client it should work, still if you want error handling
try {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + (year + '').substring(2))
}catch(e){
document.write('Today');
}

You can get the last two digits of day by doing String(year).substring(2,4). So you end up with:
console.log(day+"/"+month+"/"+String(year).substring(2,4));
To set defaults you can use the following:
var demo = value1 || default
You can play around with these ideas here

Related

How to manipulate a date that is fetched from an html input with javascript

I am trying to get a date from an html input to javascript, substract 3 years from it and then place the new date back into another html date input field.
I got the substraction to work with the current date but I can not get it to work when I fetch a date from an html input.
Below my code that works:
<input id="InputDate" data-role="datepicker"/>
<input id="OutputDate" data-role="datepicker"/>
<script type="text/javascript">
var dt = new Date(); // this line I want to replace with the next 2 lines!
//var inDate= document.getElementById("InputDate").value;
//var dt = new Date(inDate);
dt.setFullYear(dt.getFullYear() - 3);
var datestring = ("0" + dt.getDate()).slice(-2) + "." + ("0"+(dt.getMonth()+1)).slice(-2) + "." + dt.getFullYear();
document.getElementById("OutputDate").value = datestring;
When I fetch a date from the input field I get 'aN.aN.NaN' back into the output field.
I have tried document.getElementById("InputDate").valueAsDate instead, but this did not work either.
When I place an alert(dt) after the instantiation of dt I get 'Invalid Date'.
Any suggenstions how to get the fetched date in the DateObject correctly?
Regards, Manu
Just need to pass correct format to date() function:
//var dt = new Date(); // this line I want to replace with the next 2 lines!
var inDate= document.getElementById("InputDate").value;
inDate = inDate.split(".");
var dt = new Date(inDate[2],inDate[1],inDate[0]);
//alert(dt);
dt.setFullYear(dt.getFullYear() - 3);
var datestring = ("0" + dt.getDate()).slice(-2) + "." + ("0"+(dt.getMonth()+1)).slice(-2) + "." + dt.getFullYear();
document.getElementById("OutputDate").value = datestring;
<input id="InputDate" data-role="datepicker" value="19.05.2015"/>
<input id="OutputDate" data-role="datepicker"/>
var inputValues = document.getElementById("InputDate").value.split(".");
var dt = new Date(inputValues[2], inputValues[1] - 1, inputValues[0]);
If you get something like 22.12.1985 as InputDate value
first verify your ,document.getElementById("InputDate").value; is
returning correct date
var inDate= document.getElementById("InputDate").value;
var dt = new Date(Date.parse(inDate)); //use parse input to corret date format
dt.setFullYear(dt.getFullYear() - 3);
Use date format
var date = "2017-06-19";//yyyy-mm-dd or mm-dd-yyyy
var dt = new Date(date);
console.log(dt);
//output Mon Jun 19 2017 00:00:00 GMT+0545 (Nepal Standard Time)
// if you want to set the date to new output text box
var newDate = dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();
console.log(newDate);
var d = document;
d.g = d.getElementById;
var inDate = d.g("InputDate");
var outDate = d.g("OutputDate");
var datestring = "";
var mo = "";
var dt = null;
inDate.onchange = function() {
dt = new Date(inDate.value);
dt.setFullYear(dt.getFullYear() - 3);
datestring = ("0" + (dt.getMonth() + 1)).slice(-2) + "." + ("0" + dt.getDate()).slice(-2) + "." + dt.getFullYear();
outDate.value = datestring;
};
<input id="InputDate" data-role="datepicker" value="mm.dd.yyyy"><input id="OutputDate" data-role="datepicker" />
This revision makes use of the onchange event attribute which avoids the "NaN" message displaying in response to the default value of "mm.dd.yyyy" which serves as a prompt for the user. It also uses some short-cuts to reduce the verbosity of the code. Note: while the official example elegantly splits on a "." to get the date values, taking the time to use the Date methods to extract the month, day and year has an advantage despite the extra code. Splitting on a "." works as long as the input data contains a period to demarcate the month, day and year values. But the user could instead use a "/" or a "-" and then that splitting code would not yield the correct result, unless there was code that checked for the period.

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

Add X days to a typed in date

I have some JavaScript code that adds 10 days to the date typed into a text box and prints it into another text box, except that instead of updating the month, it just sets the day to 31+, which is obviously a problem.
This is the text box:
Job Completion Date:
<input type="date" name="completion_date" onblur="autofill_date_1(this.value)">
I have a second text box that is supposed to be updated when the text box is clicked out of:
Report Due Date:
<input type="text" name="due_date" id="autofill_1" readonly>
This is the JavaScript code that updates the day, except it does not update the month if the day exceeds the last day of the month:
function autofill_date_1(formDate) {
var interval = 10;
var startDate = new Date(Date.parse(formDate));
var month = startDate.getUTCMonth() + 1;
var day = startDate.getUTCDate();
var year = startDate.getUTCFullYear();
var expDate = month + "-" + (day + interval) + "-" + year;
new_text = document.getElementById("autofill_1");
new_text.value = newDate;
};
I see why this has the problem that it does but I don't have any experience working with dates. There are a lot of answers already about a similar issue but none of them are helping with the way I am trying. What would be the best way to fix this issue, maybe a completely different way altogether?
You could do this using getTime:
function autofill_date_1(formDate){
var interval = 10;
var startDate = new Date(Date.parse(formDate));
// Assuming the above date parses well:
var expDate = new Date(startDate.getTime() + interval * 86400000);
var month = expDate.getUTCMonth() + 1;
var day = expDate.getUTCDate();
var year = expDate.getUTCFullYear();
var expDate = ('0' + month).substr(-2) + "-" + ('0' + day).substr(-2) + "-" + year;
new_text = document.getElementById("autofill_1");
new_text.value = expDate;
}
Here's an example of some simple date arithmetic which should be enough to get you going:
var date1 = new Date("10/Dec/2015 20:30:00");
var daysToAdd = 30;
date1.setDate(date1.getDate() + daysToAdd)
document.write(date1.getDate() + "/" + (date1.getMonth()+1) + "/" + date1.getFullYear());
Actually here is a very simple and elegant solution. The comments in the code should make it clear, but you might want to read up on the Date object and its methods to fully understand it. You can test the snippet at the bottom of this post :)
var dueDate = document.getElementById('due-date'),
repDate = document.getElementById('report-date');
dueDate.addEventListener('blur', function(e) {
var repDateObj= new Date(this.value),
nrOfDays = 10; // nr. of days to report in second input
repDateObj.setDate(repDateObj.getDate()+nrOfDays);
// [].join('-') is the same as doing item1 + '-' + item2 + '-' etc...
repDate.value = [
repDateObj.getFullYear(),
// if the month/ date are < 10, add a leading 0 so the format is compatible with
// the format expected by date inputs (yyyy-mm-dd)
// add +1 to months because they start at 0=January
(repDateObj.getMonth() + 1 < 10 ? '0' : '') + (repDateObj.getMonth() + 1),
(repDateObj.getDate() < 10 ? '0' : '') + repDateObj.getDate()
].join('-');
}, false);
<input type="date" id="due-date">
<input type="date" id="report-date" disabled>

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

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