本文共 2458 字,大约阅读时间需要 8 分钟。
做javaWEB项目时,对于时间的处理上总会出现一些非常细致的问题,这里总结一下,方便以后查询。
一、 有时候前端显示页不是日期区间,而是就一个日期,也就是查当天的日期,比方说,就查2019-05-22这一天的数据量,这里转换到后端的意思即为查2019-05-22 00:00:00到2019-05-22 23:59:59这个日期区间的数据记录,这时候就需要转换一下:
package com.Jevin.controller; import org.junit.Test;import java.util.Calendar;import java.util.Date; public class DateUtil { /** * 获取日期的00:00:00 * @param startDate * @return */ public static Date getStartTime(Date startDate){ Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); return calendar.getTime(); } /** * 获取日期的23:59:59 * @param endDate * @return */ public static Date getEndTime(Date endDate){ Calendar calendar = Calendar.getInstance(); calendar.setTime(endDate); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.SECOND,59); return calendar.getTime(); } @Test public void test(){ System.out.println(getEndTime(new Date())); } }
二、将Date类型的时间转换为任意格式的String类型的时间,或者将String类型的时间格式转换为Date类型:
/** * 将Date类型转换为指定格式的String */ @Test public void test13(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String strDate = sdf.format(date); System.out.println(strDate); }
/** * 将String类型的时间转换为Date类型 */ @Test public void test14() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strDate = "1949-10-01 12:12:12"; Date date = sdf.parse(strDate); System.out.println(date); }
三、获得时间戳,也就是从1970年到现在的时间的毫秒数,反过来由时间戳获取时间。这个前后端分离用的比较多,一般前后端传的时间参数都是时间戳,而不是具体时间,这个时候需要我们将其解析为时间格式:
/** * 将具体时间转换为时间戳 */ @Test public void test15(){ Date date = new Date(); long timeMillis = date.getTime(); System.out.println(timeMillis); }
/** * 将时间戳转换为具体时间 */ @Test public void test16(){ String strMillis = "1558503981957"; long time = Long.valueOf(strMillis); Date date = new Date(time); System.out.println(date); }
三、数据库日期函数TIMESTAMPDIFF()可用来计算两个日期之间的差值:比方说,我需要计算2020-05-12比2019-05-01多了多少天,可以这样:
SELECT TIMESTAMPDIFF(MONTH,"2019-05-01","2020-05-12");
或者当前时间比指定日期多几天
SELECT TIMESTAMPDIFF(DAY,"2019-05-01",NOW());
转载地址:http://ygtvb.baihongyu.com/