Unbreakable Unbreakable - 3 months ago 6
HTML Question

Date in calendar sets back to current date when page is refreshed

I have one calendar on UI and initially when the page is loaded the current date should be shown in the calendar. I am achieving this by:

$('#single_cal1').attr("placeholder", new Date().toLocaleDateString());


Now If user selects another date in calendar I am able to update the date in the calendar box as per the selection.

Issue: When the page is refreshed the date in the calendar box gets back to the current date. And its evident because on page refresh my code

$('#single_cal1').attr("placeholder", new Date().toLocaleDateString());


runs and sets the date to current.

Kindly note that I have "user selected date" available in localStorage all the time.

Current Code:

<script>
$('#single_cal1').attr("placeholder", new Date().toLocaleDateString());
</script>


Code I want to achieve:

<script>
var x = localStorage.getItem('date'); // OUPTUT OF DATE IS 2016-08-19T14:22:53.339Z
var y = x.toLocaleDateString();
$('#single_cal1').attr("placeholder",y);
</script>


But I get error. And I kind of know why I am getting error. Is there any way I can format the date I got from local storage. Thanks!

Answer

You can simply do:

var y  = new Date(x).toLocaleDateString();
// new Date('2016-08-19T14:22:53.339Z').toLocaleDateString()
// returns 8/19/2016
Comments