计算日期天数差值
2016-04-28 21:21
281 查看
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class DaysBetweenTwoDate { public static boolean isLeapYear(int year){ if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return true; return false; } public static int getDayInYear(String date){ int result = 0; int[] months = {31,28,31,30,31,30,31,31,30,31,30,31}; String[] nums = date.split("-"); int year = Integer.valueOf(nums[0]); int month = Integer.valueOf(nums[1]); int day = Integer.valueOf(nums[2]); if(isLeapYear(year)) months[1] = 29; for(int i = 0; i < month-1; i++) result += months[i]; result += day; return result; } public static int getDaysBetweenTwoDates(String date1, String date2){ int year1 = Integer.valueOf(date1.split("-")[0]); int month1 = Integer.valueOf(date1.split("-")[1]); int day1 = Integer.valueOf(date1.split("-")[2]); int year2 = Integer.valueOf(date2.split("-")[0]); int month2 = Integer.valueOf(date2.split("-")[1]); int day2 = Integer.valueOf(date2.split("-")[2]); if(year1 == year2){ return getDayInYear(date2) - getDayInYear(date1) + 1; } int beforeYear1Days = (isLeapYear(year1) ? 366 - getDayInYear(date1) : 365 - getDayInYear(date1)); int betweenTwoYearDays = 0; for(int diffYear = year1 + 1; diffYear < year2; diffYear++) betweenTwoYearDays += (isLeapYear(diffYear) ? 366 : 365); int afterYear2Days = getDayInYear(date2); return beforeYear1Days + betweenTwoYearDays + afterYear2Days; } public static void main(String[] args){ System.out.println(getDaysBetweenTwoDates("2014-6-6", "2016-7-28")); System.out.println(ChronoUnit.DAYS.between(LocalDateTime.of(2014,6,6,12,12), LocalDateTime.of(2016,7,28,12,12))); } }
相关文章推荐
- 算法笔记-codeup1928-日期差值
- 【codeup 1928】日期差值
- PHP 计算Date类型的差值
- Java基础
- 自己去搭建一整套的代价足够大,不如会快捷使用它
- 微型Top源码剖析
- Ubuntu 安装 lnmp
- 【Docker】容器、虚拟机与Docker概念全解析
- MVC 下 JsonResult 的使用方法(JsonRequestBehavior.AllowGet)【转】
- 有关Java继承的一小段代码
- 【2016.4.23】【gdoi2016前模拟赛】【总结】
- HDU 2767 Proving Equivalences 强连通分量
- iOS开发总结之UIView常用属性
- SNS进阶
- 第九周 周记
- centos 6.5环境利用iscsi搭建SAN网络存储服务及服务端target和客户端initiator配置详解
- C语言的学习
- XDU-1036 分配宝藏 (DP)
- centos 6.5环境利用iscsi搭建SAN网络存储服务及服务端target和客户端initiator配置详解
- NOIP199904求Cantor表