Java后端对于时间的处理

场景

有一个批订单,我想查询某个月的所有数据,前端传过来一个时间类型的数据,需要后端做处理

解决办法

1)推荐使用

private static void calendar(Date time) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(time);
	Integer year = calendar.get(Calendar.YEAR);
	Integer month = calendar.get(Calendar.MONTH)+1;
	System.out.println("年:"+year+"===月:"+month);//年:2020===月:6
}

获取月份之所以要加1因为月份是从零开始的,这里可以获取正确的年份和月份

2)不推荐使用

@SuppressWarnings("deprecation")
private static void date(Date time) {
	Integer year = time.getYear();
	Integer month = time.getMonth()+1;
	System.out.println("年:"+year+"===月:"+month);//年:120===月:7
}

这种方式看源码就知道已经被弃用了,获取月份之所以要加1因为月份是从零开始的,获取的年份也不是传进来的年份,点进去看这个Date类,注释说从JDK 1.1版起,替换为Calendar,
原文如下:

/**
* Returns a number representing the month that contains or begins
* with the instant in time represented by this Date object.
* The value returned is between 0 and 11,
* with the value 0 representing January.
*
* @return  the month represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by Calendar.get(Calendar.MONTH).
*/
@Deprecated
public int getMonth() {
	return normalize().getMonth() - 1; // adjust 1-based to 0-based
}

3)还有另一中是用SimpleDateFormat时间格式化之后获取年份的,因为SimpleDateFormat貌似是一个线程不安全的方法,所以这里也不推进使用

你可能感兴趣的:(Springboot,MyBatis,工具)