0

In PHP, it's possible to say:

$unixTimeOfLastSunday = strtotime("last Sunday");

Which would equate to something like this: 1465714800

How would one accomplish the same thing in either Javascript or AngularJS?

EDIT - I am now using moment.js as an angular library. Here's my controller:

myApp.controller('myController', ['$scope', 'moment', function ($scope, moment) {

    moment.updateLocale('en', {
        meridiem: {
            am: 'am',
            AM: 'AM',
            pm: 'pm',
            PM: 'PM'
        }
    });

    var sunday = moment().calendar("Last Sunday at 12:00 AM");
    var sundayUnix = moment(sunday).unix();
    console.log(sundayUnix);

});

But for some reason, the console always spits out today, and not Sunday.

LatentDenis
  • 2,839
  • 12
  • 48
  • 99
  • Possible duplicate of [the closest Sunday before given date with JavaScript](http://stackoverflow.com/questions/6024328/the-closest-sunday-before-given-date-with-javascript) – SSH Oct 17 '16 at 04:40
  • See the [momentjs documentation](http://momentjs.com/docs/). Search for "Unix Epoch", there are examples of how to parse from the number and how to get the number from a moment instance. – Igor Oct 17 '16 at 19:39
  • @Igor, I tried a solution, but have failed. I edited my question accordingly, can you help? – LatentDenis Oct 17 '16 at 20:44

2 Answers2

1

I suggest using moment.js. You can combine http://momentjs.com/docs/#/displaying/calendar-time/ and http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/.

Edit: So apparently, momentjs is really awesome and anything is possible - and easy, if you explore the rich API. The answer is simply moment().day("Sunday").unix().

Beautiful if you ask me! :) Relevant documentation.

Nick Ribal
  • 1,959
  • 19
  • 26
  • Can you please elaborate using a code example? I've been at this all day! I can't seem to find the right way to do the calendar so that whatever day it is (mon-sat) it will always give me "last sunday" – LatentDenis Oct 17 '16 at 20:45
0

Using moment.js: https://momentjs.com/

In order to get the Sunday in the week prior, this works:

var sunday = moment().day(-7);

In order to get the Sunday of the current week:

var sunday = moment().day(0);

To get this day's Unix time at midnight:

var sundayMidnight = moment().day(0).startOf('day').unix();
LatentDenis
  • 2,839
  • 12
  • 48
  • 99