trailmax
trailmax

Reputation: 35106

Javascript strange date manipulation

I came across in a seemingly reputable source a strange date manipulation that I don't understand. This is part of the samples in supporting documentation for a popular UI framework:

var startDate = start.value();  // returns Date object
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());

Now line by line var startDate = start.value(); this lines returns Date object and saves it in startDate variable. Fine here, no problem.

Then we create new Date object with the same value and assign it back to the same variable (mildly confusing, but I can live with it).

Third line is a real puzzle - we get day of the month (via getDate) and assign it as a day of the month (via setDate) in the same variable.

Now the question: is this a bad code, possibly leftovers from unfinished refactoring? Or is this really making sense and it does some manipulation like removing time (does not look like it)? If it is, what does it do?

UPD: code sample is here http://demos.telerik.com/kendo-ui/datepicker/rangeselection

Upvotes: 7

Views: 111

Answers (2)

aw04
aw04

Reputation: 11177

The source is available in multiple formats, and if we inspect them all:

html5/javascript:

startDate.setDate(startDate.getDate());

asp.net:

startDate.setDate(startDate.getDate() + 1);

jsp:

startDate.setDate(startDate.getDate() + 1);

php:

startDate.setDate(startDate.getDate() + 1);

We can clearly see the first (one you linked to) stands out where they should be the same. This would lead one to believe the issue is a simple typo.

Upvotes: 3

Marco Scabbiolo
Marco Scabbiolo

Reputation: 7459

Lets go line by line:

startDate = new Date(startDate);

Will return the same date if startDate is a Date

var someDate = new Date(5555555113);
console.log(someDate);
startDate = new Date(someDate);
console.log(startDate);

But if start.value() returns either miliseconds, or a string, passing it to new Date will ensure whatever of these 3 ways to represent a Date is used, you'll get the Date object.

var someDate = 5555555113;
var startDate = new Date(someDate);
console.log(startDate);

someDate = "1970-03-06T07:12:35.113Z";
startDate = new Date(someDate);
console.log(startDate);

Now the next line:

startDate.setDate(startDate.getDate());

This doesn't make any sense, as it'll return the same Date

var startDate = new Date();
console.log(startDate);
startDate.setDate(startDate.getDate())
console.log(startDate);

Upvotes: 2

Related Questions