javascript force date into input field - javascript

i have 2 input fields for a check in date and a check out date. when the user puts in the dates it calculates the nights. However i dont want the user to be able to put a date 30 days after the check in date. Ive used an alert to bring up a message if nights is greater then 30 however the date u selected goes into the check out date. Im trying to use innerHTML to force the date in the check out to be what i want it to be ie 1 day after the check in date if they have selected more then 30 days. Heres part of my code.
function DoDepart() {
Date.fromUKFormat = function(sUK)
{
var A = sUK.split(/[\\\/]/);
A = [A[1],A[0],A[2]];
return new Date(Date.parse(A.join('/')));
}
var a = Date.fromUKFormat(document.getElementById('datepicker').value);
var b = Date.fromUKFormat(document.getElementById('departure').value);
var x = ((b - a) / (24*60*60*1000));
if (x > 30)
{
alert("check out date must be within 30 days of your check in date");
document.getElementById('departure').innerHTML = 'hey';<!--this bit must be wrong
}
document.getElementById('n').value = x;
};
any help would be appreciated

If #departure is a text input element, you should edit their value this way:
document.getElementById('departure').value= 'hey';

Related

Subtract one day from date and find values -Js

i working on small billing application using electronjs and pouchdb
i want to find the opening balance for every day based on date selection on input
if there is no data in particular date i want to find the data by the previous dates
i tried in recursive way but it did not work
// getting date value on change
var TodayDate = document.getElementById('daybook-firstdate').value;
// onchange function
function getday(TodayDate){
daybook.find({
selector: {
Date:TodayDate ,
}
}).then(function(result) {
var opening_balance = 0
//chenking the data is present in the selected date
if(result.docs.length>0){
result.docs.forEach((element, ) => {
saletotal = (isNaN(element.TotalAmount) ? 0: parseInt(element.TotalAmount));
Totalinvest = (isNaN(element.TotalInvestment) ? 0: parseInt(element.TotalInvestment));
Totalexp = (isNaN(element.TotalExpenses) ? 0: parseInt(element.TotalExpenses));
opening_balance+=saletotal+Totalinvest-Totalexp
console.log(opening_balance)
});
}
// if there is no data on particular date subtracting one day from date from date and calling the
//get day function with yesterday value as parameter to check if the data is present in previos date
else{
let d = new Date(TodayDate);
d.setDate(d.getDate() - 1);
var yesterdaydate = d.toISOString().split('T')[0];
getday(yesterdaydate)
}
});
}
//selecting the date
<input type="date" name="daybook" id="daybook-firstdate" onchange="getday()" >
i want to execute the find until there is data in previous date from selected date
any one help me with code
day book object: //find is based on Date object

assigning date values to input fields using date picker

I have a url parameter called commencing date in the format of dd-mm-yyyy. I have input fields in my html field and I need to set dates to those input fields. I need to dates to be set like this. If the commencing date(url parameter string) is 01-01-2014 , the first input field should have the date of 15-02-2015. That means 1 month and 2 weeks later. Then the next input field should have the date 1 month and 2 weeks after the 15-02-2014. This should happen say 10 times. I am doing it using a for loop.I have assigned jquery datepicker for my input fields.
var initialDate = "01-01-2014";
var x;
for(x=1; x<= 10;x++){
var dateArray = initialDate.split("-");
var dateObj = new Date(dateArray[2],dateArray[1],dateArray[0]);
dateObj.setMonth(dateObj.getMonth()+1);
dateObj.setDate(dateObj.getDate()+14);
// Assign the new date value to input field.
$("#dateOf_installment_"+x).val(dateObj.getDate()+"-"+dateObj.getMonth()+"-"+dateObj.getFullYear());
}
But this does not give me the required values. How to solve this problem, Thanks all!
2 problems with your code -
The Date object uses 0-11 instead of 1-12 for months Jan-Dec. So when you set the month of the date object, you need to subtract 1 to set the correct month. When you convert the month back to Jan-Dec 1-12, you'll need to add back the 1.
Also, I updated your code a little so that the loop will continue working correctly. This loop goes 3 iterations, but should be expandable to 10.
Lastly, if your answers come out different then expected, this thread might be the cause of the issue.
How to add number of days to today's date?
JS Fiddle: http://jsfiddle.net/biz79/bteL6138/
var initialDate = "01-01-2014";
var lastDate = initialDate;
var x;
for (x = 1; x <= 3; x++) {
var dateArray = lastDate.split("-");
// sub 1 from month
var dateObj = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
dateObj.setMonth(dateObj.getMonth() + 1);
dateObj.setDate(dateObj.getDate() + 14);
// add 1 for month
lastDate = dateObj.getDate() + "-" + (dateObj.getMonth() + 1) + "-" + dateObj.getFullYear();
$("#dateOf_installment_" + x).val(lastDate);
}

Validating a date range client side

I have 2 TextBoxes that expect a date in the format mm/dd/yyyy
Ex:
03/20/2013
Before I even bother to make the ajax call, I want to try and turn these into JS Dates. How could I check if:
Both Dates are in the mm/dd/yyyy format and if they are, then From must be less than to.
Thanks
I'd recommend using moment for this one. Moment is a js library especially for dates, and evaluating dates. Your two text boxes start off as strings, so you need to init 2 moment()'s with each. Then verify they're both moment objects. If so, it's then a simple matter to make sure the one is after the other.
Here's the link to moment: http://momentjs.com/
Here's code I may use:
var tb1 = $("#tb1").text(); // get string from "date box 1"
var tb2 = $("#tb2").text(); // get string from "date box 2"
//get timestamp val's so they can be used in moment initialization
var date1 = tb1.split("/");
var date2 = tb2.split("/");
//create moments
var mom1 = moment([date1[2], date1[1], date1[0]);
var mom2 = moment([date2[2], date2[1], date2[0]);
function validate(mom1, mom2){
//validate both dates are actual dates
if (mom1.isValid() && mom2.isValid()){
//compare timestamps to ensure 2nd timestamp is larger
if(mom1.unix() < mom2.unix()){
return true;
} else {
return false;
}
} else {
//strings aren't dates, return error
$.error("not valid dates");
}
}

Comparing dates Java Script

I have the following scenario that I am strugling to code.
I have a valuation date that is a string that is chosen by a user from a calander popup. What I need to do is take that date and pass it into a function that works outs a second date depending on the value of that date. If the first date is more than 7 days from the first day of the month use the first day of the month else use the last day of the month. This needs to happen in client side as this date need to be displayed after they have chosen the first date.
SO far I have the below:
Function CompareDate()
{ var date1 = document.getElementById("textbox1");
var x = new date();
var year = x.getYear();
var day = x.getDay();
var thisMonthFirstDay = new Date(year, month,1)
var thisMonthLastDate = ....
var 1day = 1000*60*60*24
var date1_ms = recdate
var date2ms = thisMonthFirstDay.gettime()
if(Math.round(difference_ms/1day) > 7
{var textbox = document,getelementbyid("textbox2");
textbox.value = texbox.value + thisMonthLastDate
}
else
{
textbox.value = texbox.value + thisMonthFirstDay }
}
Any examples of how this can be done would be greatly appeciated.
Cheers
getDate() will give you the day of month (e.g. 18), so if (getDate() <= 7) { outputDate = 1; } If you're having a problem getting the last day of each month for the else statement, I generally use a 12 capacity array with hard-coded values, adding 1 to February if (year % 4 == 0).
I have managed to resolve this after a finding the parseDate() function on a fiddler site. That allowed me to convert the date from this format (31 Jan 2013) to a date and then I could just use the getDay(function) to see if the day was > 7. From there it was easy!
Thanks for above suggestions.

Questions about javascript dates

I have 2 questions about dates.
The first one is how can I get the "AM/PM" from a date in Javascript?
the second question is say I have this code
var convertedStartDate = new Date(dueDate);
var month = convertedStartDate.getMonth() + 1;
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortDueDate = month + "/" + day + "/" + year;
Now as you can see I want always this format mm/dd/yyyy
So I am wondering if say dueDate is 1/9/2010 (mm/dd/yyyy) but the person entered it in as dd/mm/yyyy(some other format version of date).
would
month = 1
day = 9
year = 2010
Or do I have to tell it somehow to always convert into mm/dd/yyyy? Or does it do is own format so that it always would get the right order? Ie it does not matter what order they put the date in it would always get 9 as the day.
Here, give this a try:
now = new Date();
hour = now.getHours();
var tag = "";
if (hour >= 12) {
tag = "pm";
} else {
tag = "am";
}
As for the second part of your question, I'd just make those parts of the form separate fields, there really is no way otherwise. You're just going to have to write some hints into your form.
You need to always turn/convert whatever the user entered into a Javascript Date object. Remember - Javascript is local to the client's computer... a person in the USA will have different format settings than a person in the UK or China.
To keep things simple... suggest or present a hint near the input textbox the desired input format. Then, validate against that format using a Regex. This way you are almost guaranteed to get the desired date... well... unless the user has Javascript disabled. LOL... in that case... you need to convert on the server-side (you should always be doing this anyway).
To get the AM/PM of a time found some old code I wrote a long time ago. See the (remove am/pm) here you can replace it with a get using the substring.
function ValidateAdvancedTime(time, formatType){
time = time.replace(".", ":");
var newTime = time.substring(0, (time.indexOf(":") + 3)); // Strip out the seconds
var status = ValidateTime(newTime, formatType);
if(status == false)
return false;
var seconds = time.substring(time.indexOf(":") + 4, time.length);
if(seconds.length > 2)
**seconds = seconds.substring(0, 2); // Remove any AM/PM afterwards**
if(!isNaN(seconds)) { // Make sure its a number and it's between 0 and 59
if((seconds <= 59) && (seconds >= 0))
return true;
}
return false;
}
As far as the dates go I've never had any problems storing 1/9/2010 or 01/09/2010 in the database.

Categories