Without having to worry about timezone or anything, what's the fastest and best way to -1 day from the input=date on my form within JS, covert to string as YYYY-MM-DD so it can be parsed and used to post to API etc?
My date_to var as you can see from my date_to_selector.val() prints the string "YYYY-MM-DD" - I need to minus 1 day from this string in a new variable
Here is my code from the date input "Date To":
<input type="date" name="date_to" />
var date_to_selector = $(this).parent().find("input[name=date_to]");
var date_to = date_to_selector.val();
I've looked into this and many suggest moment.JS or toISOString but I don't want to have to worry about timezones etc.
CodePudding user response:
You can get the input's valueAsDate
property, then set its date to the day of the selected date minus 1:
$('input[type="date"]').change(function(){
const date = $(this).prop('valueAsDate')
date.setDate(date.getDate() - 1)
const res = date.toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}).split('/').join('-');
console.log(res)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="date_to" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>