dcsimg
www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 20

Thread: Add 30 days to date from userís input

  1. #1
    Join Date
    Feb 2017
    Posts
    18

    Question Add 30 days to date from userís input

    Hello everyone,

    I need to come up with a date calculator that will add either 30 days or 180 days to a date inputted by the user, depending on the second condition -e.g dropdown). The new date will be displayed in an string in an text area.

    Mockup here: https://i.imgsafe.org/367d6e2761.jpg

    Steps:
    1. User will enter start date (preferably in a format that will be easier for user to pick - from a JavaScript calendar or as in the image attached)
    2. User will select from dropdown either 30 day or 180 report value
    3. System will display new date calculated to either +30 or +180 days from the date inputted by the user and will be displayed in an textarea or plain HTML the new date; in addition to to the new date I need to be able to add some text in the textarea that will specify what documentation needs to be completed (as per mockup)

    I have tied to modify different scripts (most successful one based on the pregnancy calculator which came very close to format that I need, but of course the date calculation is wrong).
    My JavaScript skills are very limited (more of HTML guy)
    I would really appreciate your help.

    Criss

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    If you had searched for this, you would have found an existing answer for 90 days... http://www.webdeveloper.com/forum/sh...0-days-to-date all you do is change whats needed.

    Use an ISO date which is like this 2017-02-22 and works with HTML5 date input fields.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Feb 2017
    Posts
    18
    Thank you very much for your reply.

    I did search the forum and tested several scripts before posting here. In fact there are many great scripts on this site in addition to this one - that do what I need. However due to my limited skills I have not been able to successfully adapt these to what I need, my issue is pretty trivial (and a little embarrassing in fact) as I have difficulties integrating these functions into a form that uses a combination of 3 select fields (for day, month, year and report type) like to one used for the due date calculator (http://www.webdeveloper.com/forum/sh...culator-script).

    I continue to work on this as I am learning more from the scripts here. Thank you again!

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    HTML5 has a date picker that creates from that input an ISO date in the format of YYYY-MM-DD that can readily be used in the Date object and then add the required days, from there you can then create a date that is in ISO format to stuff in to another field that is also using the HTML5 date type input.

    for example, a date with a minimum of 1st Jan 2017 and a maximum of 31 Dec 2017
    HTML Code:
    <input name="dateone" type="date" min="2017-01-01" max="2017-12-31" value="" >
    and you don't need to specify a min or max if its not needed.

    as a demo...
    Code:
    function pad(n){ return (n > 9 ? "" : "0") + n; }
    function addDays( i ){
      // i is the reference to the date field, we need the value of that field
      var d = new Date( i.value ); 
      d.setDate( d.getDate() + 30 ); // add 30 days
      document.forms.dates.datetwo.value = [d.getFullYear(), pad( d.getMonth()+1) , pad(d.getDate()) ].join("-");
    }
    and HTML
    HTML Code:
    <form name="dates" action="javascript:;">
    <input name="dateone" type="date" value="" onchange="addDays(this);">
    <input name="datetwo" type="date" value="" >
    </form>
    When you select the date from the date picker in the one field, the other is automatically set on completion.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  5. #5
    Join Date
    Dec 2012
    Posts
    1,495
    Currently I do not recommend using HTML5 date input as it's not supported by all browsers:
    http://caniuse.com/#feat=input-datetime
    You can use another datepicker, e. g. that one of jQuery UI. An additional advantage is that the picker looks identical in all browsers.
    Try this:
    Code:
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        Please select a date: <input type="text" id="datepicker">
        <select id="selectoffset">
            <option value="">Select an offset</option>
            <option value="30">30 days</option>
            <option value="120">120 days</option>
        </select>
        <output id="resultingdate"></output>
        <script>
            function getResult() {
                var dateval = $("#datepicker").val();
                var offset = $("#selectoffset").val();
                if (dateval != "" && offset != "") {
                    var dat = $("#datepicker").datepicker("getDate");
                    dat.setDate(dat.getDate() + parseInt(offset));
                    $("#resultingdate").text($.datepicker.formatDate("yy-mm-dd", dat));
                }
            }
            $("#datepicker").datepicker().on("change", getResult);
            $("#selectoffset").on("change", getResult);
        </script>
    Last edited by Sempervivum; 02-15-2017 at 04:22 PM.

  6. #6
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    Quote Originally Posted by Sempervivum View Post
    Currently I do not recommend using HTML5 date input as it's not supported by all browsers:
    Even if its not fully supported in all browsers as a date picker, the field degrades to a text field and recommending using JQuery isn't the best idea either, having to load a few hundred lines of code to then do something that takes a couple of lines of JavaScript.

    Currently supported in Chrome and Opera.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  7. #7
    Join Date
    Feb 2017
    Posts
    18
    Thank you very much, this is really close to what I need!
    What would be the best way to change input date feed in the datepicker to dd/mm/yyyy (Canada, eh?). Also (once again quite embarrassing) can't figure out how to add a simple message to display along with getResult - just need to display one custom message for each instance, for example - "for 30 day you need to complete report 1" / "for 120 day you need to complete report 2". I recognize this is not really advice on code but I am just now trying to learn more about the mysteries of JavaScript. thanks again!

  8. #8
    Join Date
    Feb 2017
    Posts
    18
    This is great, thanks again. Took all the advice I could get and linked together a few lines. The roadblock I now have is changing the date feed from yyyy/mm/dd to dd/mm/yyyy. Once that is done will changing the returndate as well, for now it is in format yyyy/mm/dd to not mess the calculation. What would be the best way to do this? thanks a lot

    <script>
    function ReturnDate() {
    var returnDate = '';
    var caseStart = document.getElementById('caseStart').value;
    var requestedDays = parseInt(document.getElementById('days').value);
    var dateEnd = document.getElementById('DateEnd');
    var dateParts = caseStart.split('/').map(function(i) {
    return parseInt(i);
    });
    if (dateParts.length == 3 && !isNaN(requestedDays) ) {
    var d = new Date(
    dateParts[0],
    dateParts[1] - 1,
    dateParts[2] + requestedDays
    );
    if (!isNaN(d.getTime())) {
    returnDate ="Your Initial documentation is due by " + "\n\n " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + "\n(yyyy/mm/dd)\n" + "\n Documentation to be completed by this date: \n a. \n b. \n\c." ;
    } else {
    returnDate = 'Please enter date in format (yyyy/mm/dd)';
    }
    }
    DateEnd.value = returnDate;
    }
    </script>
    </head>
    <body>
    Enter the case start date (yyyy/mm/dd)<br>
    <input type="text" value="" name="caseStart" id="caseStart" onkeyup="ReturnDate()" />
    <br><select name="days" id="days" onChange="ReturnDate()" >
    <option selected disabled>Choose Documentation Type</option>
    <option value="30">Initial (30 days)</option>
    <option value="40">Initial (40 days)</option>
    </select>
    <p>
    <textarea class="field-style" align="left" type="text" value="" name="DateEnd" id="DateEnd" cols="70" rows="15"></textarea>
    </p>
    </body>

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    You use HTML5 date field, if HTML5 date is not supported, you input can be plain text as thats what the field defaults to.

    You can ask people to input the date as d/m/yyyy or dd/mm/yyyy abd split at the / and use .reverse() method, then pad those elements that need padding with a 0, stick it back together with join("-") and pass to a date object to make a date reference. Use setDate() to set the date with 30 days added and then get a date form the Date object. Something like here http://www.webdeveloper.com/forum/sh...25#post1496725 (further up the thread)

    You can use Regular Expressions if the Date field is not supported to ensure that your user is inputting a date. Something that can be easily found in a search.

    instead of using a onkeyup="ReturnDate()" event, use a onblur event to run when focus changes from that object, test the date field and if it does not pass, return focus with the focus() method.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  10. #10
    Join Date
    Dec 2012
    Posts
    1,495
    Date in the input field can be easily changed by handing over {dateFormat: 'dd/mm/yy'} when initializing the datepicker.
    Date in the text output can be easily changed by handing over "dd/mm/yy" when formatting date.
    Text can be easily exended by additional text components concatenated by "+".
    Code:
        Please select a date: <input type="text" id="datepicker">
        <select id="selectoffset">
            <option value="">Select an offset</option>
            <option value="30">30 days</option>
            <option value="120">120 days</option>
        </select>
        <output id="resultingdate"></output>
        <script>
            function getResult() {
                var dateval = $("#datepicker").val();
                var offset = $("#selectoffset").val();
                if (dateval != "" && offset != "") {
                    var dat = $("#datepicker").datepicker("getDate");
                    var dat1str = $.datepicker.formatDate("dd/mm/yy", dat);
                    dat.setDate(dat.getDate() + parseInt(offset));
                    var dat2str = $.datepicker.formatDate("dd/mm/yy", dat);
                    var additionaltxt;
                    if (offset == "30") additionaltxt = " for 30 day you need to complete report 1";
                    else additionaltxt = " for 120 day you need to complete report 2"
                    $("#resultingdate").text("text1 " + dat1str + " text2 " + dat2str + additionaltxt);
                }
            }
            $("#datepicker").datepicker({dateFormat: 'dd/mm/yy'}).on("change", getResult);
            $("#selectoffset").on("change", getResult);
        </script>
    Last edited by Sempervivum; 02-18-2017 at 10:24 AM.

  11. #11
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    Simple example of using a RegExp, no JQuery just wholesome JavaScript.

    HTML Code:
    .red {
    	background-color: red;
    	color: yellow;
    }
    .transparent {
    	background-color: transparent;
    }
    </style>
    <script>
    function validateDate(testdate) {
        var date_regex = /^(0?[1-9]|1\d|2\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)\d{2}$/ ;
        if( !date_regex.test(testdate.value) ) {
    	testdate.focus();
    	testdate.className="red";
        }else{
    	testdate.className = "transparent";
          
        }
    }
    </script>	
    </head>
    <body>
    <form name="date" action="javascript:;">
    	<input name="dateField1" type="text" value="" placeholder="DD/MM/YYYY" onblur="validateDate(this);">
    	<input name="dateField2" type="text" value="" readonly >
    The above example will only allow your focus to move away if the input string matches a format that is expected to be a date.

    In the `else` portion, you can conduct your calculation part and put it in to the vacant slot, as this will be autofilled, the option to make it readonly is best option to avoid manual alterning
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  12. #12
    Join Date
    Dec 2012
    Posts
    1,495
    When validating form elements one can benefit from the features of HTML5:
    Code:
        <style>
            input:invalid {
                border: 2px solid red;
            }
        </style>
        <input pattern="^(0?[1-9]|1\d|2\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)\d{2}$" required />

  13. #13
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,248
    And back to HTML5, the issue is one of support as pointed out earlier. both pattern and required are HTML5.

    pattern and required are listed as not supported in safari.

    I wrote an email to the standards people W3C and asked when are they going to kick these vendors up the butt or shame these vendors for having 8 years to produce browsers with very patchy or no support for HTML5 standard.

    Whilst uptake is purely voluntary, you'd of thought that in the name of grabbing the largest market share or retaining share of the browser markets that all the top 5 vendors would provide a level of support that was uniform and do so as fast as possible, they haven't and support is patchy, one of those browsers offering the biggest share of support is Google Chrome, which is likely why it has the biggest share of the browser market at more than 55.5% of the browsers in use daily.

    As for the suggestion for a 2 pixel border, I would rather go for something very obvious of background colour, it can't be missed by people, especially those requiring accessibility as a control in their lives, if the border was blatantly obvious like 10 pixels, then fair enough, if you have myopia or are partially sighted or someone who relies on wearing glasses to see a display, depending on the display resolution, its more likely to be missed and you would have people searching the page of inputs to find the error.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  14. #14
    Join Date
    Feb 2017
    Posts
    18
    Absolutely great, thank you very much \\.\ and Sempervivum. Impressive knowledge and skills, thank you! Ideas were great and what Sempervivum suggested was very easy for me to implement.
    Since this issue is resolved, I would like to add another feature but I run into another issue:

    I need to generate a simple .ics file for download to allow the user to save this date and information into their outlook calendar. (e.g. link "save to calendar"). I added "var icsFILE" in the script below that I would like to create a new file for download rather than display on the page. I do not know how to do this. Some other code lines I used did not run on our IE 11 (this is what we use at work). I also looked at filesaver.js blob and ics.js and they are all beyond what I can do and I feel there is a simpler solution available.



    <link href="../css/global.css" rel="stylesheet" type="text/css">
    <script src="../js/jquery-1.10.2.js"></script>
    <script src="../js/jquery-ui.js"></script>
    </script>

    <div class="form-style-9">
    <p>1. Initial Plan</p>
    <p>Enter the "Case Start Date" and select "Documentation type"
    <a href="javascript:void(0);" NAME="ongoing_1" title=" " onClick=window.open("../wind/ongoing_1.php","ongoing_1","width=505,height=280,0,status=0,scrollbars=0,toolbar=0,addressbar=0,addr ess=0,left=500,top=300,");>(click here for help)</a>:<br><i>(dd/mm/yyyy)</i>
    <br><input type="text" id="datepicker" value"dd/mm/yyyy">
    <select id="selectoffset">
    <option value="">Select documentation type</option>
    <option value="30">Initial (30 days)</option>
    <option value="40">Initial (40 days)</option>
    </select>
    <output id="resultingdate"></output>
    </p>
    </div>
    <script>
    function getResult() {
    var dateval = $("#datepicker").val();
    var offset = $("#selectoffset").val();
    if (dateval != "" && offset != "") {
    var dat = $("#datepicker").datepicker("getDate");
    var dat1str = $.datepicker.formatDate("dd/mm/yy", dat);
    dat.setDate(dat.getDate() + parseInt(offset));
    var dat2str = $.datepicker.formatDate("dd/mm/yy", dat);
    var dat3str = $.datepicker.formatDate("yymmdd", dat);
    var icsFILE = "BEGIN:VCALENDAR<br>VERSION:2.0<br>PRODID:<br>BEGIN:VEVENT<br>UID:me@company.ca<br>DTSTAMP:20170315T 170000Z<br>ATTENDEE;CN=My Self ;RSVP=TRUE:MAILTO:me@company.ca<br>ORGANIZER;CN=Me:MAILTO::me@company.ca\<br>DTSTART:" + dat3str +"\<br>DTEND:" + dat3str +"<br>LOCATION:" + additionaltxt + "<br>SUMMARY:My message<br>DESCRIPTION:My description<br>END:VEVENT<br>END:VCALENDAR";
    var additionaltxt;
    if (offset == "30") additionaltxt = "You have selected - Initial Plan (30 days)";
    else additionaltxt = "You have selected - Initial Plan (40 days)"
    $("#resultingdate").html("<div class=form-style-9> I need this to open in a separate .ics file:<br>" + icsFILE + " </div><strong><div class=form-style-9><ul type=bullet>"+ additionaltxt +"</strong><br><li>Your case start date was " + dat1str + "</li><li>Your Initial Plan documentation is due by:</li>\<strong><li>" + dat2str + "</li></strong></ul></div><div class=form-style-6><ul type=circle><strong>Documentation to be completed by this date:</strong><br><br><li> a. Create Plan ... </li></ul></div>");
    }
    }
    $("#datepicker").datepicker({dateFormat: 'dd/mm/yy'}).on("change", getResult);
    $("#selectoffset").on("change", getResult);
    </script>


    thank you!

  15. #15
    Join Date
    Dec 2012
    Posts
    1,495
    Some time ago I encountered a similar task of saving to disk and found a script download2.js. I cannot find this again but found this instead:
    http://danml.com/download.html
    Using this, saving text to disk is very easy:
    Code:
        <button id="btnsave">Save text</button>
        <script>
            document.getElementById("btnsave").addEventListener("click", function () {
                var fileName = "mytext.txt";
                var strMimeType = 'text/plain';
                download("lorem ipsum", fileName, strMimeType);
            });
        </script>
    I assume that download2.js is an advanced version but this one seems to work fine for this purpose.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles