java 获取当前时间年月日时以及生成包含当前时间之前的小时数组
要获取当前时间的年、月、日、时,可以使用Calendar类或LocalDateTime类。
使用Calendar类:
import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,所以需要加1
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
使用LocalDateTime类:
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
生成包含当前时间之前的小时数组,可以使用循环遍历从当前时间到0时之间的小时数,然后将其存入数组中:
int[] hours = new int[hour + 1]; // 创建数组,大小为当前小时数加1
for (int i = 0; i <= hour; i++) {
hours[i] = i;
}
这样,hours数组中就包含了当前时间之前的小时数
原文地址: https://www.cveoy.top/t/topic/iSbc 著作权归作者所有。请勿转载和采集!