locked
Why can't Javascript (simply) cope with dates? RRS feed

  • Question

  • User876561910 posted

    Why is it so difficult to add a number of months to today’s date in JavaScript?

    In SQL it’s really simple

    e.g.

    DateAdd("m",1,"31/01/2004")
    as 04 was a leap year the output = 29/02/2004

    DateAdd("m",1,"31-Jan-2019")
    as next year isn’t a leap year the out = 28/02/2019

    To add a number of months we do DateAdd("m",6,Date())
    so to add 6 months to day’s date and output = 11/05/2019

    It’s really simple.

    But not it seems in JavaScript. Why?

     

    Can anyone give me a really simple JS that will add 16 or 3 or 109 or 23012 months to today’s date and put it here into MyForwardDate


    I'm not going to use this - I'm just trying to learn why JS can't work with dates (simply)
    laughing

    <body>
    	<form id="MyForm" runat="server">
    		<asp:TextBox id="MyForwardDate" runat="server"></asp:TextBox>
    	</form>
    </body>
    



    Sunday, November 11, 2018 7:13 AM

Answers

  • User475983607 posted

    A bit harsh ?
    I'm not sure why.  You don't have to answer if the question offends you.

    Your question is not clear as "simply cope" is relative to your perspective.  Plus there's no source code so it is difficult to fill in the blanks.

    Yes I know I can use api’s like datejs, moment.js, jquery (date.setmonth), etc. and this would be very simple.

    I was just looking for a pure JS method.

    The APIs are open source so simply reading the code is helpful.

    The simplest method I’ve done (up to now) is to use an sql datasourse for a textbox – that works every time on any date. But this is a java study, so I’ve not used that.

    As you have stated there's no add date function in JavaScript like you find in SQL or C#.  It is up to you, the programmer, to come up with the code.  Below is an example that takes into consideration how Date.setMonth() works. Knowing that setMonth will add the number of days given by the current day of the month to the 1st day of the new month we can test the result of the day to determine if the the day is the last day of the month.  If the resulting day is less than the original day then we hit an edge case. 

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsMonthAdd.aspx.cs" Inherits="WebFormsApp.JsMonthAdd" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="myForm" runat="server">
            Add a number between 1 and 12
            <br />
            <asp:TextBox runat="server" ID="myNumber" Text="19"></asp:TextBox><br />
            Add a date<br />
            <asp:TextBox runat="server" ID="myDate" Text="2018-07-31T00:00:00"></asp:TextBox><br />
            Calculated date is here<br />
            <asp:TextBox runat="server" ID="myNewDate"></asp:TextBox><br />
            <asp:Button runat="server" Text="Click me" ID="myButton" OnClientClick="myFunction(); return false;"></asp:Button>
        </form>
    
        <script type="text/javascript">
    
            function myFunction() {
                    //Initialize the date and months to add to the date
                    var tempDate = new Date(document.getElementById('<%=myDate.ClientID%>').value);
                    var days = parseInt(document.getElementById('<%=myNumber.ClientID%>').value);
                    console.log("Start Date: " + tempDate);
    
                    //Get the starting day of the month
                    var startDay = tempDate.getDate();
                    console.log("Start Day: " + startDay);
    
                    //Set the month
                    tempDate.setMonth(tempDate.getMonth() + days);
                    console.log("Add Result: " + tempDate);
    
                    //Get the ending day of the month 
                    var endDay = tempDate.getDate();
                    console.log("End Day: " + endDay);
    
                    //If the ending day of the month is less than the starting day of the month
                    //then get the last day of the previous month.
                    var result;
                    if (startDay > endDay) {
                        var tempDate = new Date(tempDate.getFullYear(), tempDate.getMonth(), 0);
                    }
    
                console.log("Final Result: " + tempDate);
                document.getElementById('<%=myNewDate.ClientID%>').value = tempDate.getFullYear() + '-' + tempDate.getMonth() + '-' + tempDate.getDate();
            }
    
        </script>
    </body>
    </html>
    


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 14, 2018 11:58 AM

All replies

  • User-369506445 posted

    hi

    you can try below code :

    <script>
        
            dt = new Date();
            dt.setMonth(dt.getMonth() + 10)
            alert(dt);
    
       
    </script>

    Sunday, November 11, 2018 7:52 AM
  • User876561910 posted

    This will not work - – that’s one of the (many) JS’s I’ve already tried.

    Set the month add to 1 and set your computer date 31/01/2019

    It “should” give you 28/02/2019 (like it does in SQL)

    But your JS gives you

    Sun 03/03/2019

    Like I asked - WHY can't JS cope with dates simply



    Try it yourself

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <%@ Page Language="C#" %>
    <html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Untitled 1</title>
      
    
    <script>
    	function foo() {
    	var dt = new Date();
    	dt.setMonth(dt.getMonth() + 1)
    	document.getElementById("txtDateAdd").value = dt;
     }
    </script>
        
    </head>
    
    <body>
    
    <form id="form1" runat="server">
    <asp:TextBox runat="server" id="txtDateAdd"></asp:TextBox>
    	<br />
    	<br />
    	<asp:Button id="Button1" runat="server" Text="Button" OnClientClick="foo()" />
    </form>
    
    </body>
    
    </html>
    



    Sunday, November 11, 2018 8:20 AM
  • User-369506445 posted

    you can use moment library below like :

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="http://momentjs.com/downloads/moment.js"></script>
     
    <script>         
        alert(moment("20190131", "YYYYMMDD").add(1, 'months').calendar()); // 11/01/2018;    
    </script>
    

    result

    02/28/2019

    Sunday, November 11, 2018 10:27 AM
  • User876561910 posted

    Moments fail in some cases such as when months have 31 days.

    Also (important) I'm just looking for a JS not a plugin

    There MUST be a way to do this

    Of course I can simply link the page to an SQL source and load the date plus whatever months from that.
    But that's is waaaaaay too much for something as simple as this (should be)


    This problem seems to be all over the web and still no one has a simple answer
    e.g.
    https://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript

    Sunday, November 11, 2018 10:37 AM
  • User475983607 posted

    Moments fail in some cases such as when months have 31 days.

    You'll need to provide source code that reproduces this issue in Moment.js as I'm unable to reproduce.

    Also (important) I'm just looking for a JS not a plugin

    There MUST be a way to do this

    Of course I can simply link the page to an SQL source and load the date plus whatever months from that.
    But that's is waaaaaay too much for something as simple as this (should be)


    This problem seems to be all over the web and still no one has a simple answer
    e.g.
    https://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript

    Simple is a relative concept.   The JavaScript Date instance is explained here; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date. The setMonth() function is explained here; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth

    The behavior is well documented.  Also you can clearly see there's no add month in JavaScript.   There are APIs like Moment.js that handle this situation. you can write your own prototype, or do a Google search.  I'm fairly confident most of the SO posts you're viewed have a solutions to this problem.  Not to mention, Moment.js is open source and you can just look at the code.

    https://momentjs.com/docs/#/manipulating/add/

    What exactly are you asking?  Are you asking the community to write an AddMonths() JavaScript function for you according to your requirement?  Or is your question simply rhetorical as a result of frustration? 

    Sunday, November 11, 2018 2:55 PM
  • User876561910 posted

    A bit harsh ?
    I'm not sure why.  You don't have to answer if the question offends you.

    Oh well.

    Yes I know I can use api’s like datejs, moment.js, jquery (date.setmonth), etc. and this would be very simple.

    I was just looking for a pure JS method.

    No I don’t want anyone to write a function for me. This is not a “live” function it’s only a problem that I’ve seen on the web and I’m looking at various methods.

    No I’m not frustrated.

    Yes I am just trying to learn.

    The simplest method I’ve done (up to now) is to use an sql datasourse for a textbox – that works every time on any date. But this is a java study, so I’ve not used that.

    I'll work it out, but thanks for you feedback


    <script language="javascript" type="text/javascript">
    <!-- my function goes here
    function myFunction(){
    </script>
    
    
    
    <form id="myForm" runat="server">
    Add a number between 1 and 12 <br/>
    <asp:TextBox runat="server" id="myNumber"></asp:TextBox><br/>
    Add a date<br/>
    <asp:TextBox runat="server" id="myDate"></asp:TextBox><br/>
    Calculated date is here<br />
    <asp:TextBox runat="server" id="myNewDate"></asp:TextBox><br/>
    <asp:Button runat="server" Text="Click me" id="myButton" OnClientClick="myFunction"></asp:Button>
    </form>
    



    Wednesday, November 14, 2018 7:25 AM
  • User475983607 posted

    A bit harsh ?
    I'm not sure why.  You don't have to answer if the question offends you.

    Your question is not clear as "simply cope" is relative to your perspective.  Plus there's no source code so it is difficult to fill in the blanks.

    Yes I know I can use api’s like datejs, moment.js, jquery (date.setmonth), etc. and this would be very simple.

    I was just looking for a pure JS method.

    The APIs are open source so simply reading the code is helpful.

    The simplest method I’ve done (up to now) is to use an sql datasourse for a textbox – that works every time on any date. But this is a java study, so I’ve not used that.

    As you have stated there's no add date function in JavaScript like you find in SQL or C#.  It is up to you, the programmer, to come up with the code.  Below is an example that takes into consideration how Date.setMonth() works. Knowing that setMonth will add the number of days given by the current day of the month to the 1st day of the new month we can test the result of the day to determine if the the day is the last day of the month.  If the resulting day is less than the original day then we hit an edge case. 

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsMonthAdd.aspx.cs" Inherits="WebFormsApp.JsMonthAdd" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="myForm" runat="server">
            Add a number between 1 and 12
            <br />
            <asp:TextBox runat="server" ID="myNumber" Text="19"></asp:TextBox><br />
            Add a date<br />
            <asp:TextBox runat="server" ID="myDate" Text="2018-07-31T00:00:00"></asp:TextBox><br />
            Calculated date is here<br />
            <asp:TextBox runat="server" ID="myNewDate"></asp:TextBox><br />
            <asp:Button runat="server" Text="Click me" ID="myButton" OnClientClick="myFunction(); return false;"></asp:Button>
        </form>
    
        <script type="text/javascript">
    
            function myFunction() {
                    //Initialize the date and months to add to the date
                    var tempDate = new Date(document.getElementById('<%=myDate.ClientID%>').value);
                    var days = parseInt(document.getElementById('<%=myNumber.ClientID%>').value);
                    console.log("Start Date: " + tempDate);
    
                    //Get the starting day of the month
                    var startDay = tempDate.getDate();
                    console.log("Start Day: " + startDay);
    
                    //Set the month
                    tempDate.setMonth(tempDate.getMonth() + days);
                    console.log("Add Result: " + tempDate);
    
                    //Get the ending day of the month 
                    var endDay = tempDate.getDate();
                    console.log("End Day: " + endDay);
    
                    //If the ending day of the month is less than the starting day of the month
                    //then get the last day of the previous month.
                    var result;
                    if (startDay > endDay) {
                        var tempDate = new Date(tempDate.getFullYear(), tempDate.getMonth(), 0);
                    }
    
                console.log("Final Result: " + tempDate);
                document.getElementById('<%=myNewDate.ClientID%>').value = tempDate.getFullYear() + '-' + tempDate.getMonth() + '-' + tempDate.getDate();
            }
    
        </script>
    </body>
    </html>
    


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 14, 2018 11:58 AM
  • User753101303 posted

    Hi,

    You want to be always on the last day ? What if you add one month to be on 28 or 29 and then again one month ? In this case my personal preference is to work with day 1 and then I just subtract one day to get the end of the previous month (including in SQL Server).

    Wednesday, November 14, 2018 12:25 PM