简体   繁体   中英

Moment.js, custom date format and countdown from difference with callback

I am using Moment.js for this. I tried looking docs but could find a solution that helps me at this scenario.

function countDown(scheduler){
  var time = moment().local("fi").format("L hh:mm:ss");

  console.log("Current time: "+time);
  console.log("Scheduler: "+scheduler);
  console.log("Difference: "+(time-scheduler));

}

Current time: 27.07.2017 12:23:21
Scheduler: 27.07.2017 12:16:31
Difference: NaN

I am trying to get the difference between time and scheduler , then return value as minutes and it should countdown to 0 and then fire callback function

I have no idea how to parse that time to an object. I know that I have to do that before I can get the difference.

EDIT 3:

  function countDown(scheduler){

    var time = moment();
    var schedulerMoment = moment(scheduler, "L hh:mm:ss");

    console.log("Current time: " + time.local("fi").format("L hh:mm:ss"));
    console.log("Scheduler: "+scheduler);
    console.log("Difference: "+(time.diff(schedulerMoment, "minutes")));
  }
  • Current time: 07/27/2017 01:23:00
  • Scheduler: 27.07.2017 12:55:14
  • Difference: NaN

Creating moment object with custom format is supported

moment(time, format)

You can also get different in minutes like this

time.diff(scheduler, 'minutes')

So your code can look like this

function countDown(scheduler){
    var time = moment();
    var schedulerMoment = moment(scheduler, "DD.MM.YYYY hh:mm:ss");

    console.log("Current time: " + time.local("fi").format("L hh:mm:ss"));
    console.log("Scheduler: "+scheduler);
    console.log("Difference: "+(time.diff(schedulerMoment, "minutes")));
}

You can try this code :-

function countDown(schedule){ 
  var time = moment().local("fi").format("L hh:mm:ss");
  var schedule = new Date(schedule)
  var momentschedule = moment(schedule);
  console.log("Current time: "+time);
  console.log("Scheduler: "+schedule);
  var duration = moment.duration(momentschedule.diff(time));
 var minutes = duration.asMinutes();

  console.log("Difference: "+(minutes));
}
countDown("27.07.2017 12:16:31");//pass schedule date string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM