Marco Marco - 6 months ago 27
Javascript Question

Jquery - datepicker dates

I am trying to set datepicker default values for to and from fields with todays date for to field and a week back to to field, like this:

//datepicker
var date = new Date();
var date = date.toDateString();
var weekBack = new Date();
var weekBack = new Date(weekBack.setDate(weekBack.getDate() - 7));
var weekBack = weekBack.toDateString();
console.log(date);
$('#datePicker').fdatepicker({
closeButton: false,
initialDate: weekBack,
format: 'dd.mm.yyyy',
}).on('changeDate', function (ev) {
timelines();
barCharts();
});

$('#datePicker1').fdatepicker({
closeButton: false,
initialDate: date,
format: 'dd.mm.yyyy',
}).on('changeDate', function (ev) {
timelines();
barCharts();
});


But I then my both fields have the todays date.

Answer

This line:

var date = date.toDateString();

returns String, so String doesn't contain the getDate() method.

Just don't use it var date = date.toDateString();.

var date = new Date();
var weekBack = new Date(date.setDate(date.getDate() - 7));
// weekBack is Fri May 13 2016 17:36:12 GMT+0300 (Russia TZ 2 Standard Time) for me

If you want to get weekBack as a timestamp don't wrap it with new Date:

var date = new Date();
var weekBack = date.setDate(date.getDate() - 7);
// weekBack is 1463150337387

[UPD] The example are here - https://jsfiddle.net/ht4eg4zs/