参考地址:
How to set datetime to end of day in java - Stack Overflow
-
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
-
- public class TestDate {
- public static void main(String[] args) throws ParseException {
- method1();
- method2();
- System.out.println(getDateEndDay(new Date()));
- }
-
- public static void method1() throws ParseException {
- Calendar cal = Calendar.getInstance();
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
- SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
- SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
- String str1 = sdf1.format(cal.getTime());
- String str2 = sdf2.format(cal.getTime());
-
- System.out.println(str1);
- System.out.println(str2);
-
- Date startDate = sdf3.parse(str1);
- System.out.println(startDate);
-
- Date endDate = sdf3.parse(str2);
- System.out.println(endDate);
-
-
- }
-
- public static void method2() throws ParseException {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- Date startDate = cal.getTime();
-
- cal.set(Calendar.HOUR_OF_DAY, 23);
- cal.set(Calendar.MINUTE, 59);
- cal.set(Calendar.SECOND, 59);
- cal.set(Calendar.MILLISECOND, 999);
- Date endDate = cal.getTime();
-
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println(sdf.format(startDate));
- System.out.println(sdf.format(endDate));
- }
-
- private static Date getDateEndDay(Date date) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.set(Calendar.HOUR_OF_DAY, 23);
- cal.set(Calendar.MINUTE, 59);
- cal.set(Calendar.SECOND, 59);
- cal.set(Calendar.MILLISECOND, 999);
- return cal.getTime();
- }
- }