Kwhitejr Kwhitejr - 3 months ago 9
Javascript Question

How to programmatically determine the prior time period based upon unix time stamps in Javascript?

Essentially I have two unix timestamps, representing the first and last days of a given month. Is it possible programmatically determine the timestamps for the first and last of the previous month?

For example, I have the following two timestamps:

1467331201
-->
July 1, 2016


1469923201
-->
July 31, 2016


Essentially, can I manipulate these two numbers in a consistent way in order to the unix time (or Date object) for June 1, 2016 and June 30, 2016, respectively? Problem that I'm running into is that you cannot simply subtract a given amount because the amount of days in a month is variable.

Answer

You could use this function:

function getPreviousMonthRange(unixTime) {
    var dt = new Date(unixTime * 1000);
    dt.setUTCDate(0); // flips to the last day of previous month
    var unixLast = dt.getTime();
    dt.setUTCDate(1); // back to the first day of that same month
    var unixFirst = dt.getTime();
    return [unixFirst / 1000, unixLast / 1000];
}

// given first and last date (only one is really needed)
var unixTimeFirst = 1467331201;
var unixTimeLast = 1469923201;

// get previous month's first & last date
var [first, last] = getPreviousMonthRange(unixTimeFirst);

// output
console.log('previous month first day: ', first, new Date(first*1000));
console.log('previous month last day: ', last, new Date(last*1000));

Comments