Search code examples
angularjsunixmomentjsangular-moment

How to get UNIX time with moment.js with particular string format "last ..."?


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.


Solution

  • 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.