JAVA时间类型

本文介绍JAVA的几种时间类型的使用:Date、Calendar、LocalDate 、LocalTime、LocalDateTime、Instant

Date

#获取当前时间
Date date = new Date(); #Thu Dec 30 11:59:02 CST 2021

#格式化当前时间1
Date date = new Date();
DateFormat df2 = DateFormat.getDateTimeInstance();
String format = df2.format(date);  #2021-12-30 12:00:05

#格式化时间2
Date date = new Date()
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String value = format.format(date); #2021-12-30 12:00:05
#获取时间戳的三种方式
long l = System.currentTimeMillis();
long timeInMillis = Calendar.getInstance().getTimeInMillis();
long time = new Date().getTime();

        date获取年月日的方法基本已经作废了就不演示了

Calendar

我们可以把Calendar看做是Date类的增强版,因为Calendar类提供了一组方法,允许将一个以毫秒为单位的时间转换成年、月、日、时、分、秒、星期等。我们可以把Calendar类看做是万年历,默认显示的是当时间,同时也可以查看其他时间。如下:(其实,Calendar底层也是通过new Date() 获取Date实例)

#获取当前时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
Date date2 = calendar.getTime();
String value= dateFormat.format(date2)

#获取年
int year = calendar.get(Calendar.YEAR); 

#获取月
int month = calendar.get(Calendar.MONTH)+1;       //月(从0开始,故要+1):11

#获取本月当前时间的日 月有28-31天
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); #方案1
int day = calendar.get(Calendar.DATE);#方案2

#获取本年当前的日 年有365-366天
int dayOfYear   = calendar.get(Calendar.DAY_OF_YEAR); 

#获取当前时间小时
int hourOfDay   = calendar.get(Calendar.HOUR_OF_DAY);  #时(24小时制)
int hour  = calendar.get(Calendar.HOUR);          #时(12小时制)

#获取当前时间 分
int minute = calendar.get(Calendar.MINUTE);      

#获取当前时间 秒
int second = calendar.get(Calendar.SECOND);

#获取当前时间毫秒
int millisecond = calendar.get(Calendar.MILLISECOND);

#获取星期几 先判断一周的第一天是不是星期天;如果是,则-1;
int dayOfWeek = calendar.getFirstDayOfWeek() == Calendar.SUNDAY ? calendar.get(Calendar.DAY_OF_WEEK) - 1 : calendar.get(Calendar.DAY_OF_WEEK);

LocalDate 只包含年月日

获取年月日 

#获取当前 年 月 日
LocalDate today = LocalDate.now(); #2021-12-30

//构造指定的年月日
LocalDate localDate = LocalDate.of(1998, 12, 10); #结果2019-09-10

#获取当前 年
LocalDate today = LocalDate.now(); 
int year = today.getYear();

#获取当前 月
LocalDate today = LocalDate.now();
Month month = today.getMonthValue();

查询 | 修改年份日期等

#获取当前日期是 本周的第几天
LocalDate today = LocalDate.now();
int value = today.getDayOfWeek().getValue();

#获取当前日期是本月的第几天
LocalDate today = LocalDate.now();
int value = today.getDayOfMonth();

#获取当前日期是本年的第几天
LocalDate today = LocalDate.now();
int value = today.getDayOfYear();

#修改该日期的年份
LocalDate today = LocalDate.now();
LocalDate localDate = today.withYear(1998);  #结果 1998-12-30

#修改当前的日期的月份
LocalDate today = LocalDate.now();
LocalDate localDate = today.withMonth(2); #结果 2021-02-28

#修改该日期当月的天数
LocalDate today = LocalDate.now();
LocalDate localDate = today.withDayOfMonth(12);

 判断比较

#判断是否是闰年
LocalDate today = LocalDate.now();
boolean leapYear = today.isLeapYear();

#判断该年是356还是366天
LocalDate today = LocalDate.now();
int value = today.lengthOfYear();

#当前月份有多少天
LocalDate today = LocalDate.now();
int value = today.lengthOfMonth();

#比较该日期月其他日期的大小,返回正数 ,那么当前的对象时间较晚(数字较大)
LocalDate today = LocalDate.now();
LocalDate today2 = LocalDate.now();
int value = today.compareTo(today2);

#比较该日期是否比参数日期早(true为早)
LocalDate today = LocalDate.now();
LocalDate today2 = LocalDate.now();
LocalDate localDate = today2.withMonth(4); #只能判断年月日,时分秒无法判断,所以这里修改了月份 4
boolean before = localDate.isBefore(today);

#比较该日期是否比参数日期晚(true为晚)
LocalDate today = LocalDate.now();
LocalDate today2 = LocalDate.now();
LocalDate localDate = today2.withMonth(4);
boolean before = localDate.isAfter(today); 

#比较两个日期是否相等
LocalDate today = LocalDate.now();
LocalDate today2 = LocalDate.now();
LocalDate localDate = today2.withMonth(4);
boolean before = localDate.isEqual(today);

在原有的年份上增加年份

#在该日期增加指定年数,也就是当前年份 +n 年
LocalDate today = LocalDate.now();
LocalDate localDate = today.plusYears(3);

#在该日期增加指定月份,也就是当前月+ n 月
LocalDate today = LocalDate.now();
LocalDate localDate = today.plusMonths(3);

#在该日期增加指定周数,也是n周后的日期
LocalDate today = LocalDate.now();
LocalDate localDate = today.plusWeeks(1);

#在该日期增加指定的天数,例如今天30号+1 就是31号
LocalDate today = LocalDate.now();
LocalDate localDate = today.plusDays(1);

在原有的年份上减少年份

#在该年份上减少年份, 例如2021年减1=2020
LocalDate today = LocalDate.now();
LocalDate localDate = today.minusYears(1);

#在该月份上减少月份, 例如12月减1=11月
LocalDate today = LocalDate.now();
LocalDate localDate = today.minusMonths(1);

#在该日期减少指定的周数, 例如今天8号减1=1号
LocalDate today = LocalDate.now();
LocalDate localDate = today.minusWeeks(1);

#在该日期减少指定天数,今天30号,减1=29号
LocalDate today = LocalDate.now();
LocalDate localDate = today.minusDays(1);

LocalTime 只包含日期

#获取当前时间
LocalTime time = LocalTime.now(); # 10:42:57.151

#格式化 当前时间
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
String format = df.format(now); # 11:49:52

#构造指定时间
LocalTime specificTime = LocalTime.of(12, 12, 12, 12); #结果 12:12:12.000000012

#时区指定(Asia/Shanghai,GMT+8)
LocalTime timeKolkata = LocalTime.now(ZoneId.of("GMT+8"));  #10:48:52.490 

LocalDateTime 包含日期和时间 *使用推荐*


#获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
#获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();

#获取当前时间
LocalDateTime nowTime= LocalDateTime.now(); #2021-12-30T11:43:28.219

#当前时间格式化
LocalDateTime nowTime= LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");# 2021-12-30 11:44:32

#自定义时间 of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
LocalDateTime endTime = LocalDateTime.of(2021, 12, 30, 12, 10, 11,00);  #2021-12-30T12:10:11

#获取年份
LocalDateTime nowTime = LocalDateTime.now();
int year = nowTime.getYear();

#获取月份
LocalDateTime nowTime = LocalDateTime.now();
int monthValue = nowTime.getMonthValue();

#获取日
LocalDateTime nowTime = LocalDateTime.now();
int dayofMonth = nowTime.getDayOfMonth();

#时
LocalDateTime nowTime = LocalDateTime.now();
int hour = nowTime.getHour();

#分
LocalDateTime nowTime = LocalDateTime.now();
int minute = nowTime.getMinute();

#秒
LocalDateTime nowTime = LocalDateTime.now();
int second = nowTime.getSecond();

#星期几
LocalDateTime nowTime = LocalDateTime.now();
DayOfWeek dayofWeek = nowTime.getDayOfWeek();

#今天是今年的第几天
LocalDateTime nowTime = LocalDateTime.now();
int dayofYear = nowTime.getDayOfYear();

判断比较

#比较该日期是否比参数日期早(true为早)
boolean isBefore = nowTime.isBefore(endTime);、

#比较该日期是否比参数日期晚(true为晚)
 boolean isAfter = nowTime.isAfter(endTime);
 
 #比较两个日期是否相等(true为相等)
 boolean euqal =nowTime.equals(endTime);

 在原有的年份上减少年份

#在该年份上减少n年份, 例如2021年减1=2020
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusYears = nowTime.minusYears(1);


#在该月份上减少n月份, 例如12月减1=11月
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusMonths = nowTime.minusMonths(1);

#在该日期减少n的周数, 例如今天8号减1=1号
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime BeforeWeek = nowTime.minusWeeks(1);

#在该日期减少n天数, 例如今天30号,减1=29号
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusDays = nowTime.minusDays(1);

#在该日期减少n小时, 例如现在11点减1=10点
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusHours = nowTime.minusHours(1);

#该日期减少n分钟, 例如现在60分减1=59分
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusMinutes = nowTime.minusMinutes(1);

#该日期减少n秒钟,例如现在60秒减1=59秒
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusSeconds = nowTime.minusSeconds(1);

#灵活的减少 params1,指定增加的数;params2 指定要减少年,月,日还是时,分,秒
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime minusTime = nowTime.minus(3, ChronoUnit.MONTHS);

在原有的年份上增加年份

#在该日期增加指定年数,也就是当前年份 +n 年
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusYears = nowTime.plusYears(1);

#在该日期增加指定月份,也就是当前月+ n 月
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusMonths = nowTime.plusMonths(1);

#在该日期增加指定周数,也是n周后的日期
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime AfterWeek = nowTime.plusWeeks(1);

#在该日期增加指定的天数,例如今天30号+1 就是31号
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusDays = nowTime.plusDays(1);

#在该日期增加n小时, 例如现在10点加1=11点
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusHours = nowTime.plusHours(1);

#该日期增加n分钟, 例如现在59分加1=60分
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusMinutes = nowTime.plusMinutes(1);

#该日期增加n秒钟, 例如现在59秒加1=60秒
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusSeconds = nowTime.plusSeconds(1);

#灵活的增加 params1,指定增加的数;params2 指定要增加年,月,日还是时,分,秒
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusTime = nowTime.plus(3, ChronoUnit.MONTHS);

 Instant

#获取当前时间戳
Instant now = Instant.now(); #以ISO-8601输出   2021-12-30T03:23:33.167Z 时间少了八小时
Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));  #时间正常 不少八小时

#格式化当前时间
Instant now = Instant.now();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault());
String format = dateFormat.format(now); #2021-12-30 11:54:24 没有少八小时

#获得当前时间戳并且增加n毫秒
Instant instant1 = Instant.now().plusMillis(3);
#获得当前时间戳并且减少n毫秒
Instant instant2 = Instant.now().minusMillis(3);

#比较该日期是否比参数日期晚(true为晚)
instant.isAfter(instant1);

#比较该日期是否比参数日期早(true为早)
instant.isBefore(instant1); 

#比较两个日期是否相等(true为相等)
instant.equals(instant1);


#获得当前时间戳并增加1小时 通过TimeUnit.HOURS.toMillis(1)将小时转换为毫秒,然后通过plusMillis增加
Instant instant3 = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(1));

#获取时间戳instant和instant3相差天数,返回long类型,如果小于1天,都算零天,大于等于1天,小于2天算一天
 instant.until(instant3, ChronoUnit.DAYS); 
 
#获取时间戳instant和instant3相差的小时数,返回long类型
instant.until(instant3, ChronoUnit.HOURS); 

#获取时间戳instant和instant3相差的毫秒数,返回long类型
 instant.until(instant3, ChronoUnit.MILLIS);

 实用案例

实体类中可以用这个注解在字段上
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date modifyDate;   

时间格式的区别:

2019-12-31 to yyyy-MM-dd: 2019-12-31
2019-12-31 to YYYY-MM-dd: 2020-12-31

y:year-of-era;正正经经的年,即元旦过后;
Y:week-based-year;只要本周跨年,那么这周就算入下一年;
就比如说今年(2019-2020) 12.31 这一周是跨年的一周,而 12.31 是周二,那使用 YYYY 的话会显示 2020,使用 yyyy 则会从 1.1 才开始算是 2020。

H

小时(24小时制)

HH:mm:ss --> 14:53:11

h

小时(12小时制)

HH:mm:ss --> 14:53:11

  jsp页面转换时间戳

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
  
  

 ajax返回时间格式转换

function renderTime(date) {
    var dateee = new Date(date).toJSON();
    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

 获取昨天日期

   public static String getYesterdayStr() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -1);
        SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return startSdf.format(c.getTime());
    }

 获取上周第一天

public static String getWeekStartDay() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_WEEK,2);
		c.add(Calendar.DATE, -7);
		SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd  00:00:00");
		return startSdf.format(c.getTime());
	}

获取上周最后一天

	public static String getWeekEndDay() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_WEEK,2);
		c.add(Calendar.DATE, -1);
		SimpleDateFormat endSdf = new SimpleDateFormat("yyyy-MM-dd  23:59:59");
		return endSdf.format(c.getTime());
	}

获取上月第一天

public static String getMonthStartDay() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
		SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-01  00:00:00");
		return startSdf.format(c.getTime());
	}

 获取上月最后一天

	public static String getMonthEndDay() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
		SimpleDateFormat endSdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
		return endSdf.format(c.getTime());
	}

 常用时间转换工具类

public class DateUtils {

    /**
     * Date转LocalDate
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
    /**
     * LocalDateTime转毫秒时间戳
     * @param localDateTime LocalDateTime
     * @return 时间戳 1640828236888
     */
    public static Long localDateTimeToTimestamp(LocalDateTime localDateTime) {
        try {
            ZoneId zoneId = ZoneId.systemDefault();
            Instant instant = localDateTime.atZone(zoneId).toInstant();
            return instant.toEpochMilli();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 时间戳转LocalDateTime
     * @param timestamp 时间戳
     * @return LocalDateTime
     */
    public static LocalDateTime timestampToLocalDateTime(long timestamp) {
        try {
            Instant instant = Instant.ofEpochMilli(timestamp);
            ZoneId zone = ZoneId.systemDefault();
            return LocalDateTime.ofInstant(instant, zone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Date转LocalDateTime
     * @param date Date
     * @return LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        try {
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            return instant.atZone(zoneId).toLocalDateTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * LocalDateTime转Date
     * @param localDateTime LocalDateTime
     * @return Date
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        try {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = localDateTime.atZone(zoneId);
            return Date.from(zdt.toInstant());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * String转Date
     * @param String dateStr
     * @return Date
     */
      public static Date stringToDate(String dateStr){
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = format1.parse(dateStr);
                return date
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
      }  
}

网上案例:

统计昨天、当月、上月、本周的SQL语句
统计上周的数据:
select * from tb where datediff( wk, C_DATETIME, '2010-01-25 13:43:47.000') = 1
select * from tb where datediff( wk, C_DATETIME, getdate() ) = 1
统计昨天的数据:
SELECT * FROM `orders` WHERE DAY(ordertime)=(DAY(NOW())-1)   //能使用 
统计当月的数据:
select * from tb where datediff(mm,C_DATETIME,'2009-10-30 15:05:00.170')=0 --当月
select * from tb where datediff(mm,C_DATETIME,getdate())=0 --当月
统计当年的数据:
select * from tb where datediff(year,C_DATETIME,'2009-10-30 15:05:00.170')=0  --当年
select * from tb where datediff(year,C_DATETIME,getdate())=0  --当年
统计上月的数据:
select * from tb where month(C_DATETIME)=(month('2009-07-30 15:05:00.170')-1) --group by Userid  --上月的
select sum(Marks),Userid from BBSScore where month(CreateDate)=(month(getdate())-1) group by Userid
 
select * from dbo.Web_UserAccount where datediff(week,C_DATETIME,getdate())=0     --C_DATETIME为日期字段        本周:
select * from dbo.Web_UserAccount where datediff(Month,C_DATETIME,getdate())=0   --C_DATETIME为日期字段        本月:
select * from dbo.Web_UserAccount where datediff(qq,C_DATETIME,getdate())=0        --C_DATETIME为日期字段         本季:
select * from dbo.Web_UserAccount where datepart(mm,C_DATETIME)/7 = datepart(mm,getdate())/7            --前半年1-6,后半年7-12:
 
 
 
一天 "select * from T_news where datediff(day,addtime,getdate())=0";
三天 "select * from T_news where datediff(day,addtime,getdate())<= 2 and datediff(day,addtime,getdate())>= 0";
一周 "SELECT * FROM T_news WHERE (DATEPART(wk, addtime) = DATEPART(wk, GETDATE())) AND (DATEPART(yy, addtime) = DATEPART(yy, GETDATE()))";
一月"SELECT * FROM T_news WHERE (DATEPART(yy, addtime) = DATEPART(yy, GETDATE())) AND (DATEPART(mm, addtime) = DATEPART(mm, GETDATE()))";
一季度 "select * from t_news where DATEPART(qq, addtime) = DATEPART(qq, GETDATE()) and DATEPART(yy, addtime) = DATEPART(yy, GETDATE())";
其中T_news是表名,addtime是数据库中对于的时间列

个人案例

SELECT COUNT(*) FROM `orders` WHERE DAY(ordertime)=(DAY(NOW())-1) AND state=1 #昨天待发货订单
SELECT COUNT(*) FROM `orders` WHERE DAY(ordertime)=(DAY(NOW())-1) AND state>=1 #昨天成交订单


SELECT COUNT(*) FROM `orders` WHERE DAY(ordertime)=(DAY(NOW())) AND state=1 #今日待发货订单
SELECT COUNT(*) FROM `orders` WHERE DAY(ordertime)=(DAY(NOW())) AND state>=1 #今日成交订单


SELECT COUNT(*) FROM `orders` WHERE WEEK(ordertime)=(WEEK(NOW())) AND state=1 #本周待发货订单
SELECT COUNT(*) FROM `orders` WHERE WEEK(ordertime)=(WEEK(NOW())) AND state>=1 #本周成交订单

SELECT COUNT(*) FROM `orders` WHERE MONTH(ordertime)=(MONTH(NOW())) AND state=1 #本月待发货订单
SELECT COUNT(*) FROM `orders` WHERE MONTH(ordertime)=(MONTH(NOW())) AND state>=1 #本月成交订单

ordertime 时间字段

oracle中时间转换

字符串转date

SELECT * from  WHERE TO_DATE('1994-06-07', 'yyyy-mm-dd')=字段名

date转字符串

SELECT * FROM   employees
WHERE  to_char(字段名,’yyyy-mm-dd’)=’2019-10-1’

中文年月日

查询员工表中的入职时间为1994年06月07日
Select * from employees where to_char(hire_date,'yyyy"年"mm"月"dd"日"') = '1994年06月07日'

以上小编学习开发中使用&总结,如果对你有帮助就帮忙点个小赞(^人^),如有侵权联系小编!

你可能感兴趣的:(笔记&小案例,java,sql,mysql,oracle,javascript)