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

Loi*_*int 7 cron node.js

cronjob 时间语法"* * * * * *"如下 npm

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

Arm*_*yan 11

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
Run Code Online (Sandbox Code Playgroud)

  • 尽管 **CRON 的语法/格式通常为 5 个值**(以空格分隔),但它也可以是 6 或 7 个值 [请参阅此链接](https://web.archive.org/web/20111025080042/http ://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger)...在早期的 [cron](https://en.wikipedia.org/wiki/Cron) Wikipedia 中提到过您引用的文章,我也看到了在现实世界中部署的示例。 (3认同)

Sha*_*ane 5

我不知道是否有任何图书馆。但您可以使用简单的日期函数简单地实现它。

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();
Run Code Online (Sandbox Code Playgroud)

然后,您可以构建一个字符串并在 cron 模块中使用这些值。