user2128
user2128

Reputation: 640

unable to add two date values angular js

I have implemented a magnifyChart function where I need to add two time values. But when i do so, it is considering it as a string and concatenating it instead. Eventhough when i perform subtraction on those two values, it gives correct result. How do i get correct result on adding two date values?

function magnifyChart (timeA, timeB) {
    var newTimeA;
    var newTimeB;
    var quarterSize = Math.floor((timeB - timeA) / 4);
    logger.info("timeA", timeA); //Fri Sep 08 2017 17:45:19 GMT-0400 (EDT)
    logger.info("timeB", timeB); //Sun Oct 01 2017 16:01:51 GMT-0400 (EDT)
    logger.info("quarterSize", quarterSize); //495248155
    newTimeA = Math.floor(parseInt(timeA) + parseInt(quarterSize));
    newTimeB = Math.floor(timeB - quarterSize);
    logger.info("newTimeA", newTimeA); 
    logger.info("newTimeB", newTimeB);//1506392863689
    return [timeA + quarterSize, timeB - quarterSize];
}

Upvotes: 0

Views: 44

Answers (2)

RobG
RobG

Reputation: 147353

If timeA and timeB are Date objects, then in:

newTimeA = Math.floor(parseInt(timeA) + parseInt(quarterSize));

the expression parseInt(timeA) will coerce timeA to string first, then attempt to parse it to number, which might return a number or NaN.

To fix that, the simplest way is to use unary + operator:

newTimeA = +timeA + quarterSize;

There is no need for Math.floor since both values are already integers and adding them must produce another integer.

The expression +timeA will return its time value, which is specified to be an integer (or NaN, but Math.floor won't fix that) and quarterSize must be an integer from Math.floor in:

var quarterSize = Math.floor((timeB - timeA) / 4);

When you subtract two dates, the - operator coerces both to number first, so timeB - timeA "works" without any special treatment.

You generate newTimeA and newTimeB but don't use them for anything, so I presume they're for debug only.

So your code reduces to:

function magnifyChart (timeA, timeB) {
    var quarterSize = Math.floor((timeB - timeA) / 4);
    return [+timeA + quarterSize, +timeB - quarterSize];
}

If you want to return Dates instead of time values, do:

    return [new Date(+timeA + quarterSize),
            new Date(+timeB - quarterSize)];

NB In the case of +timeB - quarterSize, unary + isn't required since subtraction will coerce the Date to a number anyway, however it's likely useful for maintenance to keep the code consistent.

Upvotes: 1

user125661
user125661

Reputation: 1568

You can use date.getTime() to convert a date to an integer (timestamp). After doing the math, you can convert it back to a date by doing new Date(integer).

Upvotes: 0

Related Questions