用java写一个时间转cron表达式
时间: 2023-01-11 21:55:36 浏览: 693
好的,我们可以使用 Java 8 的 java.time 包来实现这个功能。
首先,我们需要使用 LocalDateTime 来表示时间,并使用 DateTimeFormatter 来将其转换为字符串。然后,我们可以使用 String.split() 方法将字符串拆分成数组,并使用数组中的每个元素来构建 cron 表达式。
例如:
```
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeToCron {
public static void main(String[] args) {
// 定义时间
LocalDateTime dateTime = LocalDateTime.now();
// 使用 DateTimeFormatter 格式化时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd HH mm ss");
String formattedDateTime = dateTime.format(formatter);
// 拆分字符串
String[] dateTimeParts = formattedDateTime.split(" ");
// 构建 cron 表达式
String cron = String.format("%s %s %s %s %s %s", dateTimeParts[5], dateTimeParts[4], dateTimeParts[3],
dateTimeParts[2], dateTimeParts[1], dateTimeParts[0]);
System.out.println(cron);
}
}
```
这段代码会将当前时间转换为 cron 表达式,并将其输出到控制台。
注意:cron 表达式的每一部分(秒、分、时、日、月、星期)都是从左到右依次对应时间中的年、月、日、时、分、秒,因此我们需要使用 String.format() 方法来按照正确的顺序构建 cron 表达式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)