Reputation: 13
This is my code to display a DateTime selector with the dropdown in HTML,
<input id="FromDate" name="FromDate" style="width:90%" type="datetime-local" >
I use the following JQuery code to set the date to the previous month,
var dt = new Date();
var Fromdatetime = dt.getFullYear() + "-" + ("0" + (dt.getMonth())).slice(-2) + "-" + ("0" + dt.getDate()).slice(-2) + "T" + ("0" + dt.getHours()).slice(-2) + ":" + ("0" + dt.getMinutes()).slice(-2) + ":" + ("0" + dt.getSeconds()).slice(-2) ;
$("#FromDate").val(Fromdatetime)
After I execute the script, DateTime is set up correctly to a value one month before. But after that, I'm unable to modify the date-time using the HTML element as like before.
Can anyone suggest a solution for this?
Thanks in advance
Upvotes: 1
Views: 1265
Reputation: 14570
The month are calculated from 0
to 11
so if you want to get current month you need to add +1
to you getMonth() function in JS - thats how it works.
Also, the reason you date is not updated is that you need to set attr
instead of val() to your input.
Working Demo: https://jsfiddle.net/usmanmunir/23h4L0fu/
Run snippet below to see it working.
var dt = new Date();
//Adding +1 to months
var Fromdatetime = dt.getFullYear() + "-" + ("0" + (dt.getMonth() + 1)).slice(-2) + "-" + ("0" + dt.getDate()).slice(-2) + "T" + ("0" + dt.getHours()).slice(-2) + ":" + ("0" + dt.getMinutes()).slice(-2) + ":" + ("0" + dt.getSeconds()).slice(-2);
//Using attr
$('#FromDate').attr('value', Fromdatetime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="FromDate" name="FromDate" style="width:90%" type="datetime-local">
Upvotes: 1