java获取时间(今天,昨天,上周第一天,本周第一天,本周最后一天)
Posted 捡黄金的少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java获取时间(今天,昨天,上周第一天,本周第一天,本周最后一天)相关的知识,希望对你有一定的参考价值。
1、获取当前时间(年月日时分秒)
Date date = new Date();//获得系统时间.
SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss");
String nowTime = sdf.format(date);
Date time = sdf.parse(nowTime);
2、获取昨天时间(年月日时分秒)
Date dNow = new Date(); //当前时间
Date dBefore = new Date();
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.DATE, -1); //设置为前一天,一个月也是这么设置
dBefore = calendar.getTime(); //设置为前一天时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
String defaultStartDate = sdf.format(dBefore); //格式化一天前
System.out.println("查询时间" + defaultStartDate);
3、获取今天凌晨
public static Date getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
4、获取第二天凌晨
public static Date getTimesnight() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 24);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
5、本周第一天(本周开始第一天)
public static Date getWeekStartDate(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date date = cal.getTime();
return date;
}
6、本周最后一天
public static Date getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
7、上周第一天
public static Date getSunday() {
Calendar cal = Calendar.getInstance();
//将每周第一天设为星期一,默认是星期天
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.add(Calendar.DATE, -1*7);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
8、本月第一天
public static Date getTimesMonthmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
以上是关于java获取时间(今天,昨天,上周第一天,本周第一天,本周最后一天)的主要内容,如果未能解决你的问题,请参考以下文章
SQL语句获取当天,昨天,本周,上周,本月,上月的起始时间和结束时间
js 获取昨天,今天,本周,上周,季度等时间范围(封装的js)