java计算两个日期相差月数
1.计算两个日期相差月数,不满一月按一月算
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
public static void main(String[] args) throws ParseException {
System.out.println(getMonthSpace("2020-09-29", "2020-10-27"));
}
/**
* 获取两个日期相差多少个月
*/
public static int getMonthSpace(String date1, String date2)
throws ParseException {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
int i = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
int month = 0;
if (i<0)
{
month = -i*12;
}else if(i>0)
{
month = i*12;
}
result = (c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH)) + month;
return result == 0 ? 1 : Math.abs(result);
}
2.sql语句计算两个日期时间差
select now() 获取当前日期 年月日 时分秒
select curdate() 获取当前日期 只有年月日
select curtime() 获取当前日期 只有时分秒
计算两个指定日期的月差
SELECT TIMESTAMPDIFF(month,'2020-02-29','2020-04-01') AS DiffDate
计算指定日期与当前日期月差
SELECT TIMESTAMPDIFF(month,'2020-02-28',(select curdate())) AS DiffDate
计算天的
SELECT DATEDIFF('2008-12-29','2008-12-28') AS DiffDate
记录一个方法
Date creditDate = new Date();
//格式化日期的对象(转化成习惯的时间格式)
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
String date_out = formatter.format(creditDate).toString();
formatter.format()这个方法可以将日期转换为指定格式
像 Sun Feb 28 00:00:00 CST 2020
这样格式也可以进行转换
十二个月的日期
SELECT a.price,b.time2 from
(select original_value as price,FROM_UNIXTIME( UNIX_TIMESTAMP(c.create_time),'%m' ) as mon
from asset_info c where FROM_UNIXTIME( UNIX_TIMESTAMP(c.create_time),'%Y' ) = '2020' GROUP BY mon) a
RIGHT JOIN (SELECT '01' as time2 from DUAL UNION ALL
SELECT '02' as time2 from DUAL UNION ALL
SELECT '03' as time2 from DUAL UNION ALL
SELECT '04' as time2 from DUAL UNION ALL
SELECT '05' as time2 from DUAL UNION ALL
SELECT '06' as time2 from DUAL UNION ALL
SELECT '07' as time2 from DUAL UNION ALL
SELECT '08' as time2 from DUAL UNION ALL
SELECT '09' as time2 from DUAL UNION ALL
SELECT '10' as time2 from DUAL UNION ALL
SELECT '11' as time2 from DUAL UNION ALL
SELECT '12' as time2 from DUAL )b on a.mon = b.time2
原文作者:YXWik6
原文地址: https://blog.csdn.net/YXWik/article/details/109332181
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/YXWik/article/details/109332181
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章