1

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

1
  • Glad to hear that. Thanks Commented Jul 6, 2020 at 9:25

1 Answer 1

1

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">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.