Java日期、时间的使用
在项目开发中往往离不开对日期时间的操作,提到日期时间对象,第一时间会想到Java标准类库中的Date类,但是由于Date类存在种种问题,关于Date类的操作的很多api都已经过时,Java SE8中引入了一些全新的日期时间处理api-LocalDate、LocalDateTime。
Date类
java.util.Date
Date nowDate = new Date();
System.out.println(nowDate);
// 转换成yyyy-MM-DD HH:mm:ss
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowDateFormat = simpleDateFormat.format(nowDate);
System.out.println(nowDateFormat);
虽然Date类还有getDay、getMonth、getYear等方法,但是并不推荐使用这些方法(因为很可能未来的JDK会移除这些被标记的API)。
LocalDateTime
日期时间判断API
判断两个日期时间是否在同一天
使用org.apache.commons.lang3.time.DateUtils包下的isSameDay方法
DateUtils.isSameDay(Date1, Date2);
源代码
/**
* <p>Checks if two date objects are on the same day ignoring time.</p>
* <p>检查两个日期对象是否在同一天忽略时间</p>
*
* <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
* 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
* </p>
*
* @param date1 the first date, not altered, not null
* @param date2 the second date, not altered, not null
* @return true if they represent the same day 如果它们代表同一天,则为true
* @throws IllegalArgumentException if either date is <code>null</code>
* @since 2.1
*/
public static boolean isSameDay(final Date date1, final Date date2) {
if (date1 == null || date2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
final Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
final Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return isSameDay(cal1, cal2);
}
可以使用LocalDateTime的isEqual,Api判断日期是否相等
对象.isEqual(对象)
例:
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime now2 = LocalDateTime.now();
System.out.println(now.isEqual(now2));
}
}
源代码
/**
* Checks if this date-time is equal to the specified date-time.
* <p>
* This checks to see if this date-time represents the same point on the
* local time-line as the other date-time.
* <pre>
* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
* a.isEqual(b) == false
* a.isEqual(a) == true
* b.isEqual(a) == false
* </pre>
* <p>
* This method only considers the position of the two date-times on the local time-line.
* It does not take into account the chronology, or calendar system.
* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},
* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.
*
* @param other the other date-time to compare to, not null
* @return true if this date-time is equal to the specified date-time
*/
@Override // override for Javadoc and performance
public boolean isEqual(ChronoLocalDateTime<?> other) {
if (other instanceof LocalDateTime) {
return compareTo0((LocalDateTime) other) == 0;
}
return ChronoLocalDateTime.super.isEqual(other);
}