如何使用nodejs将一般时间转换为cronjob时间?

时间:2017-05-08 03:53:49

标签: node.js cron

cronjob时间语法,例如"* * * * * *"cron npm

我希望将时间从"2017-05-09T01:30:00.123Z"转换为cron作业时间格式。有库或方法可以实现吗?

2 个答案:

答案 0 :(得分:0)

I don't know if there is any library for it or not.

But you can simply implement it using simple date functions.

var date=new Date("2017-05-09T01:30:00.123Z");

var mins=date.getMinutes();
//mins variable for the 1st * and so on 
var secs=date.getSeconds();

var dayofmonth=date.getDate();

var month=date.getMonth();

var dayofweek=date.getDay();

You can then build a string and use those values in the cron module.

答案 1 :(得分:0)

const dateToCron = (date) => {
    const minutes = date.getMinutes();
    const hours = date.getHours();
    const days = date.getDate();
    const months = date.getMonth() + 1;
    const dayOfWeek = date.getDay();

    return `${minutes} ${hours} ${days} ${months} ${dayOfWeek}`;
};

const dateText = '2017-05-09T01:30:00.123Z';
const date = new Date(dateText);

const cron = dateToCron(date);
console.log(cron); //30 5 9 5 2

仅供参考,您提到 "* * * * * *" 作为 cron 的语法/格式是不正确的。正确的格式由5 个以空格分隔的值(而不是 6 个值)组成。