Calculate date from user input - javascript

I'm trying to create a sort of Date Calculator widget, where dates can be generated based on user inputs to different fields. Thought being if you didn't know the exact date bbut knew it was so many months/years/days ago, you could generate the date using this widget. In this example, I want to find the date of an event "X" months ago. User inputs number of months ago in field, then a calculation is made to output to the text string saying, the date of the procedure was xx/xx/xxxx.
Here's my fiddle.
html:
Today’s Date:
<label for="monthsago" class="col-sm-2 control-label">How many Months ago?</label>
Date of Procedure was xx/xx/xxxx.
In all the examples I see here or by googling, it seems the dates are being set in the date object like new Date(2000, 0, 1); I want to use the input fields to generate the date objects calculated. I'm very much a novice at javascript so this is throwing me for a loop. Any input/help greatly appreciated.

Why not just subtract the month from a date object
$('#months').on('input', function () {
var date = new Date();
var month = date.getMonth();
date.setMonth(month-this.value);
$('#procedureMonths').text(date.toString());
});
FIDDLE

Related

Calculating date field based on another date field

I need to create a form with 2 date fields.
User will enter first date field (start-date) and I need to calculate 4 weeks from start date in the second date field (one-month-expiry). Better still: is there a way to calculate 1 calendar month instead of weeks?
I've managed to get the second field to populate a date - but it's not correct.
This is JavaScript, which I don't really understand. I've managed to get this far just by googling.
<script type="text/javascript">
document.getElementById('one-month-expiry').value
= (new Date(document.getElementById('start-date').valueAsDate
+ (6.04e+8 * 4)))
.format("dd/MM/yyyy");
</script>
It keeps returning the same date (29/01/1970). So I've obviously managed to stuff something up.
Any ideas how to include the first date field as part of my calculation?
<script type="text/javascript">
let date = new Date(document.getElementById('start-date').valueAsDate);
date.setMonth(date.getMonth() + 1);
document.getElementById('one-month-expiry').value = date.format("dd/MM/yyyy");
</script>
Beware that this might have some issues with edge cases. For example, adding one month to 31st January will give you 31st February, which does not exist, causing the date to roll over to 2nd March instead.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

how can I disable particular date of input type="date" from JavaScript

I have input type="date" in my html page and I want to disable particular date through JavaScript. How can I do that?
I have tried to disable using getElementById but its disabling complete date input.
You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.
<input name="somedate" type="date" min="2017-11-25">
The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);
What we can’t do yet, however, is eliminate classes of days from our input. We can’t, for example, prevent selection of weekends or disallow Mondays purely through markup. Instead, we’ll need to do a little more work, using the HTML5 validation API, and the native JavaScript Date object.
code that will display an error if the date selected is a Monday.
var date = document.querySelector('[type=date]');
function noMondays(e){
var day = new Date( e.target.value ).getUTCDay();
// Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday
if( day == 1 ){
e.target.setCustomValidity('OH NOES! We hate Mondays! Please pick any day but Monday.');
} else {
e.target.setCustomValidity('');
}
}
date.addEventListener('input',noMondays);
You could set a maximum/minimum on your date attribute like shown over here: https://www.w3schools.com/tags/att_input_min.asp
This however does not let you disable specific dates. If you really want this I would check if the selected date is allowed on posting the form.
You could get the selected date value on a submit like this in JQuery:
$('#submit').on('click', function(){
var date = new Date($('#date-input').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
//Check here if date, month and year combination is allowed
});
In this example we have a date element with id 'date-input' and a button with id 'submit'.
Note that you should also check if the date is allowed on the server side.

Adding months to setMonth of javascript showing a 0

I'm running to an issue I'm not sure how to resolve it; so the deal is that I have a function of javascript that take the date selected from the user and depending of another selection it adds to the date 6 o 12 months, the weird thing is that when you select a date of June, and make it add the 6 months I get a return value of 0 months, and it should be 12 for December, also If you choose December and add 12 months I'm getting a 0 as a return value. So here is my code
var date1 = $("#date_begin").val();
var days= date1[0] + date1[1];
var month= date1[3] + date1[4];
var year= date1[6] + date1[7] + date1[8] + date1[9];
var actualDate = new Date(year,month,days);
actualDate.setMonth(actualDate.getMonth() + 6);//add 6 months
$("#date_finish").val(actualDate.getDate()+"-"+actualDate.getMonth()+"-"+actualDate.getFullYear());
I'm printing the date directly to the text box as you can see. Also for the selection of the date in the first box I'm using the datepicker of jquery with this option selected
$("#date_begin").datepicker("option", "dateFormat", "dd-mm-yy");
I have been trying to fix this but I have no idea how to do it.
Hope you guys can give me a hand.
Months are indexed from 0.
June is 5 not 6.
What you have calculated is actually July (6) + 6 months = January (0) of the next year.
If you can get the date string into a format accepted by Date's constructor, that might be an easier way to create your date object. Though you need to be aware that there are some differences between browsers when it comes to the formats that are accepted.
If the date comes from users, then you should use a date format that makes sense for your users, and if necessary use a library that can work with that format of date.
When the date comes from communications with the server, I like to use the same format produced by JSON.stringify (dates that look like 2015-06-09T21:42:25.816Z), and I use es5-shim.js to make sure that the new Date(string) constructor can read strings in that format.
There is some information about parsing date strings using the new Date(string) constructor on Mozilla's developer site.

how can you figure out the week from a single date

I am building a project and in that project the user is going to input a date eg. 8/2/2011. then i am going to show them the information for the week that contains 8/2/2011. How can you figure out which week to show? for this project i am using javascript, jquery, and php.
You should be able to do what you want by getting the first day of the week the given date occurs in.
If your weeks start on Monday:
Date.prototype.lastMonday=function(){
var d= new Date(this), weekstart= 1;
while(d.getDay()!== 1) d.setDate(d.getDate()-1)
return d;
}
alert(new Date().lastMonday())
//returns the current date if does fall on a Monday
If you want to know the days that compose the week you can just find out the day of the week and show the appropriate days before and after. To know the day of the week just use the getDay method of the Date object(see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getDay). For more info on the Date object see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date.

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources