private DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化一下时间
Date dNow = new Date(); //当前时间
Date dBefore = new Date();
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
dBefore = calendar.getTime(); //得到前一天的时间
String defaultStartDate = dateFmt.format(dBefore); //格式化前一天
defaultStartDate = defaultStartDate.substring(0,10)+" 00:00:00";
String defaultEndDate = defaultStartDate.substring(0,10)+" 23:59:59";
---------------------------------------------------------------------------------------------------------
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Description:日期操作工具类
*/
public class DateUtil {
/**
* 日期格式:yyyy-MM-dd HH:mm:ss
*/
public static final String DATE_LONG = "yyyy-MM-dd HH:mm:ss";
/**
* 日期格式:yyyy-MM-dd
*/
public static final String DATE_SHORT = "yyyy-MM-dd";
/**
* 日期格式:yyyy-MM
*/
public static final String MONTH_SHORT = "yyyy-MM";
/**
* 获取当前时间字符串
*
* @return
*/
public static String getNowString() {
return dateFormat(new Date());
}
/**
* 从时间格式化字符串
* 默认格式为:yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String dateFormat(Date date) {
return dateFormat(date, DATE_LONG);
}
/**
* 从时间格式化字符串
*
* @param date
* @param format
* @return
*/
public static String dateFormat(Date date, String format) {
if (date == null) {
date = new Date();
}
if (format == null || format.equals("")) {
format = DATE_LONG;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* 从字符串格式化时间
*
* @param dateStr
* @param format
* @return
*/
public static Date dateFromString(String dateStr, String format) {
if (!dateStr.equals("") && !format.equals("")) {
DateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 增加时间数
*
* @param date
* @param field
* @param interval
* @return
*/
public static Date addOnField(Date date, int field, int interval) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(field, interval);
return ca.getTime();
}
/**
* 获取某个块
*
* @param date
* @param field
* @return
*/
public static int getFieldOfDate(Date date, int field) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(field);
}
/**
* 去除时分秒
*/
public static Date getCleanDate(Date date) {
date = date == null ? new Date() : date;
String cleanDateStr = DateUtil.dateFormat(date, DateUtil.DATE_SHORT);
return DateUtil.dateFromString(cleanDateStr, DateUtil.DATE_SHORT);
}
}
----允许转发,需附带原作本人/ 不允许非法盗用
Java 8时间和日期API-- LocalDate、LocalDateTime -获取各自指定时间-获取前一天时间0点到24点