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貌似是一个线程不安全的方法,所以这里也不推进使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值