这个是我自己再项目中写到的
可以借鉴
//获取当天开始时间:00:00:00
private static Date getDayStartTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.getTime();
return calendar.getTime();
}
//获取当天结束时间23:59:59
private static Date getDayEndTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
//获取本周开始时间
public static String getWeekStart(){
Calendar cal=Calendar.getInstance();
cal.add(Calendar.WEEK_OF_MONTH, 0);
cal.set(Calendar.DAY_OF_WEEK, 2);
Date time=cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
//获取本周结束时间
public static String getWeekEnd(){
Calendar cal=Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
cal.add(Calendar.DAY_OF_WEEK, 1);
Date time=cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
//获取本月开始时间
public static String getMonthStart(){
Calendar cal=Calendar.getInstance();
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date time=cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
/**
* 获取本月最后一天
* @return String
* **/
public static String getMonthEnd(){
Calendar cal=Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
Date time=cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
/**
* 获取本年的第一天
* @return String
* **/
public static String getYearStart(){
return new SimpleDateFormat("yyyy").format(new Date())+"-01-01 00:00:00";
}
/**
* 获取本年的最后一天
* @return String
* **/
public static String getYearEnd(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH,calendar.getActualMaximum(Calendar.MONTH));
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date currYearLast = calendar.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast)+" 23:59:59";
}
//运行结果
public static void main(String[] args) {
System.out.println("获取今天开始的时间:"+getDayStartTime());
System.out.println("获取今天结束的时间:"+getDayEndTime());
System.out.println("获取今天:"+getToday());
System.out.println("获取昨天:"+getYestoday());
System.out.println("获取本月开始日期:"+getMonthStart());
System.out.println("获取本月最后一天:"+getMonthEnd());
System.out.println("获取本周的第一天:"+getWeekStart());
System.out.println("获取本周的最后一天:"+getWeekEnd());
System.out.println("获取本年的第一天:"+getYearStart());
System.out.println("获取本年的最后一天:"+getYearEnd());
}
打印运行结果如下文章来源:https://www.toymoban.com/news/detail-549362.html
文章来源地址https://www.toymoban.com/news/detail-549362.html
到了这里,关于JAVA获取本日,本日开始时间本周、本月和本年的第一天和最后一天的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!