Bazinga777
Bazinga777

Reputation: 5281

How to compare values of two timestamps

I need to check for a condition where in i need to find out if two timestamps are from separate days.

I tried using timestamp.getDate and then checking

if (currentTimestamp.getDate() > previousTimestamp.getDate() )

The problem arises when the two values would belong to two seperate months, how can I go about this in pure Javascript ?

Upvotes: 0

Views: 224

Answers (3)

RobG
RobG

Reputation: 147363

There are a number of ways to achieve this.

If currentTimestamp is a string, just get the date parts (year, month, day) and compare. You haven't shown the format so how you do that is up to you.

If currentTimestamp is a date, you can use nnnnnn's suggestion and compare the date strings:

if (currentTimestamp.toDateString() == previousTimestamp.toDateString())

However since the value of toDateString is implementation dependent, should only be used within the host, strings should not be compared across hosts.

If you don't mind modifying the Date value, then:

if (currentTimestamp.setHours(0,0,0,0) == previousTimestamp.setHours(0,0,0,0))

will also return true if both are on the same day. If you don't want to change the dates, copy them first:

if (new Date(+currentTimestamp).setHours(0,0,0,0) == new Date(+previousTimestamp).setHours(0,0,0,0))

Whatever suits.

And as Matt notes, your concept of "day" should be clarified to local day or UTC day (or any other time zone) since times near the start and end of a local day are likely on different UTC (or other time zone) days, and vice versa.

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150020

Using the .toDateString() method should do it:

if (currentTimestamp.toDateString() != previousTimestamp.toDateString() ) {
    // different days
}

That method returns the date as a string without the time, in a format like "Fri Apr 15 2016" - but the specific format is irrelevant since your stated problem is just to figure out if the two timestamps are on the same day.

Upvotes: 0

xdevs23
xdevs23

Reputation: 3994

var dateObj = currentTimestamp.getDate();
var month = dateObj.getUTCMonth() + 1;
//months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var dateObjOld = previousTimestamp.getDate();
var dayOld = dateObjOld.getUTCDate();
var monthOld = dateObjOld.getUTCMonth() + 1;
var yearOld = dateObjOld.getUTCFullYear();
if(year > yearOld && month > monthOld && day > dayOld) {
    // currentTimeStamp is newer. Do stuff
}

See this answer https://stackoverflow.com/a/2013332/4479004

Upvotes: 0

Related Questions