-1

I have this bit of code:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="TextBox1" Text="10/20/2013" onchange="javascript:MyFunc();"></asp:TextBox>
        <asp:TextBox runat="server" ID="TextBox2" Text=""></asp:TextBox>
    </div>
    </form>
    <script type="text/javascript">
        function MyFunc() {
            MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
            MyTextBox2 = document.getElementById("<%= TextBox2.ClientID %>");
            var date = new Date(MyTextBox.value);
            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear() + 1;
            MyTextBox2.value = day + "/" + month + "/" + year;
        }
    </script>
</body>

Which basically is 2 textboxes and when the first textbox date is updated the second textbox value becomes the date from textbox 1 + 1 year.

The code works fine except for one issue. In Textbox1 the date must be in the US format mm/dd/yyyy which is wrong. For example if I want to change 20/10/2013 into 20/10/2014 I must enter 10/20/2013 in the first textbox.

How can I get it to work for dd/mm/yyyy?

sd_dracula
  • 3,796
  • 28
  • 87
  • 158
  • Have you tried anything? Do you understand how the current code works? – zerkms Jul 15 '13 at 11:30
  • And there was no suitable already given answer to this already asked question found here @ stackoverflow? – KooiInc Jul 15 '13 at 11:32
  • Yes, have tried the toString() methods of the Date() but not sure how to get it in the dd/mm/yyyy format. I can get it into something like 15 July 2013 for example – sd_dracula Jul 15 '13 at 11:33
  • See this post: http://stackoverflow.com/questions/3117262/javascript-date-objects-uk-dates – Chris Jul 15 '13 at 11:35
  • Just a general hint: use [moment.js](http://momentjs.com) if you want to easy manipulate date/time – xmikex83 Jul 15 '13 at 11:52

2 Answers2

1

The Date constructor can't directly take the dd/mm/yyyy format, so you will have to parse the date input:

var temp = MyTextBox.value.split('/');
var date = new Date(temp[2], temp[1]-1, temp[0]);

The above parses the day, month and year from the text input, then passes each value to the Date constructor. This works because this is one of the overloads for the constructor. Note that the month is zero based, so you need to decrement it by 1.

From MDN:

new Date(year, month, day [hour, minute, second, millisecond]);

MrCode
  • 63,975
  • 10
  • 90
  • 112
-1

try this

var s1 =  [d1.getDate(), d1.getMonth(), d1.getFullYear()].join('/');

it works see this fiddle

Vinod Louis
  • 4,812
  • 1
  • 25
  • 46