2
\$\begingroup\$

This is how I achieved it:

<script type="text/javascript">

// Get this monday
var dif, d = new Date();
dif = (d.getDay() + 6) % 7;
d = new Date(d.getTime() - dif * 24*60*60*1000);
d.setHours(0,0,0);
var thisMondayUnixtimestamp = Math.round((d.getTime() / 1000));

console.log('thisMondayUnixtimestamp', thisMondayUnixtimestamp);

// Get last monday
var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
  , day = beforeOneWeek.getDay()
  , diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
  , lastMonday = new Date(beforeOneWeek.setDate(diffToMonday));
lastMonday.setHours(0,0,0);
var lastMondayUnixtimestamp = Math.round(lastMonday.getTime() / 1000);

console.log('lastMondayUnixtimestamp = ', lastMondayUnixtimestamp);

</script>

This works. Today is 24th of Jan 2016 and the timestamp values parsed returns the following:

last Monday:
string '11/01/2016 01:00:00' (length=19)

this Monday:
string '18/01/2016 01:00:00' (length=19)

Although this works, I am uncertain if it's correct and reliable as I have put the above together from snippets found via googling.

Is there a more elegant way to do this?

\$\endgroup\$
1
  • \$\begingroup\$ @Marvin updated the question. \$\endgroup\$
    – Latheesan
    Commented Jan 24, 2016 at 21:53

1 Answer 1

3
\$\begingroup\$

I would suggest you use a date library like moment.js for this. That way, you don't have to do this all over again. With that library, it's just a few subtraction calls.

<script type="text/javascript">

By default, the browser executes JS. type is not required. The only time type is every used is if you want to tell the browser that it contains something not JS, preventing it from executing as JS.

24*60*60*1000

60 * 60 * 24 * 7 * 1000

These are constants. I suggest you use const with the convention of uppercase and underscores. If you can't use const, var will have to do but the naming convention stays.

new Date().getTime()

Use Date.now(). It's the same as new Date().getTime() without the Date object that it generates. Also, your code uses a lot of Date objects when the operation can be done with millisecond manipulation. Try avoiding the creation of objects when necessary.

setHours mutates the date object hours using local time. This means the hours you set are midnight local time. Unless this is something you intended or something UI only, this may cause issues with timekeeping.

In some regions, weeks start on a Sunday. "This Monday" may refer to the Monday that comes after that Sunday. "Last Monday" may also refer to this week's Monday that already passed. This makes the phrase "This Monday" and "Last Monday" vague.

Anyways, here's my take on it. Not much of a departure, but there's some notable changes.

(function() {
  'use strict'

  const WEEK_IN_MS = 604800000;
  const DAY_IN_MS = 86400000;
  const DAY_MONDAY = 1;

  function getDateThisMonday() {

    // start with today's midnight
    let today = new Date();
    today.setHours(0, 0, 0);

    // We start the week with Monday, we assign 7 when its a Sunday (0)
    let dayToday = today.getDay() || 7;

    // Calculate milliseconds elapsed since Monday
    let msSinceMonday = ((dayToday - DAY_MONDAY) * DAY_IN_MS);

    // Subtract today midnight with the diff to get midnight of the Monday
    let mondayTime = today.getTime() - msSinceMonday;

    return mondayTime;
  }

  // This is pretty much the same except we subtract an additional week.
  function getDateLastMonday() {
    return getDateThisMonday() - WEEK_IN_MS;
  }

  document.write('Last Monday: ' + new Date(getDateLastMonday()));
  document.write('This Monday: ' + new Date(getDateThisMonday()));

}());

\$\endgroup\$
2
  • \$\begingroup\$ Thanks your your time & comments, much appreciated. Also your take on this works quite well. Thanks again. \$\endgroup\$
    – Latheesan
    Commented Jan 24, 2016 at 22:43
  • \$\begingroup\$ I am using this in a Titanium Appcelerator project. This helper method will be inside a lib dir (e.g. DateHelper.js). A class needs to be created like this: exports.methodName = function() { ... }; so I am not sure if I can use the new javascript features. So, I have done my own take on yours and this works for me in my project: pastebin.com/wRtbufsb \$\endgroup\$
    – Latheesan
    Commented Jan 24, 2016 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.