MySQL和Java中关于时间日期汇总(持续更新)

最近在写SQL的时候,总是会遇到很多SQL相关的日期时间问题,汇总于此,便于查看。

1.获取上个月最后一个工作日的日期(java版本)


  Calendar cal1 = Calendar.getInstance();

  int month = cal1.get(Calendar.MONTH) + 1;

  int year = cal1.get(Calendar.YEAR);

  int day = cal1.get(Calendar.DATE);

  System.out.println(year + "年" + month + "月" + day + "日");

  int week = 0;

  Calendar cal = Calendar.getInstance();

  cal.set(Calendar.YEAR, year);

  cal.set(Calendar.MONTH, month - 1);

  int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);// 获取该月最大一天

  cal.set(Calendar.DAY_OF_MONTH, lastDay);

  week = cal.get(Calendar.DAY_OF_WEEK) - 1 == 0 ? 7 : cal.get(Calendar.DAY_OF_WEEK) - 1;// 获得最后一天是星期几

  if (week == 7) {

   lastDay = lastDay - 2;

  } else if (week == 6) {

   lastDay = lastDay - 1;

  }

  if (day == lastDay) {

   System.out.println("今天是本月的最后一个工作日");


  } else {

   System.out.println("今天不是是本月的最后一个工作日");


  }


2.获取当前日期往后推迟一个月

 

t1.`CREATEDATE` between (select date_add(now(),interval-1 MONTH)) and now()

3.获取所有当年年月

select case when length(mon)=1 then concat(left(CURRENT_DATE,5),'0',mon) else concat(left(CURRENT_DATE,5),mon) end months from (select @m:=@m+1 mon from tableName,(select @m:=0) a ) aa limit 12;

 

3.获取当前日期

select curdate();

4.获取当月最后一天
select last_day(curdate());

5.获取本月的第一天
select date_add(curdate(),interval -day(curdate())+1 day) ;

6.获取下个月的第一天
select date_add(curdate() - day(curdate()) +1,interval 1 month );

7.获取当前月已过了几天
select day(curdate());

8.获取当前月的天数(先加一个月,再减今天是第几天,得到当前月的最后一天,最后求最后一天是几号)
select day(date_add( date_add(curdate(),interval 1 month),interval -day(curdate()) day ));

9.上个月的第一天
select date_sub(date_sub(date_format(now(),'%y-%m-%d'),interval extract(
day from now())-1 day),interval 1 month)


10.上个月的最后一天:
select date_sub(date_sub(date_format(now(),'%y-%m-%d'),interval extract(
day from now()) day),interval 0 month) as date

11.获取当前时间(yyyy-MM-dd HH:mm:ss):

select  now()


 

你可能感兴趣的:(SQL)