• } } /* * 天数计算 */ public int totleDays(){ isRunYear(); int totle = 0; for(int i=0;i totle = totle+months[i]; } totle =totle+this.day; return totle; } /* * 判断用户输入是否存在 */ public void is...

package com.huangtao.sxt;
public class YearMonthDay {
private int year;
private int month;
private int day;
//使用一个静态数组变量
public static int[] months={31,28,31,30,31,30,31,31,30,31,30,31};
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public YearMonthDay(){
}
public YearMonthDay(int year, int month, int day) {
super();
this.year = year;
this.month = month;
this.day = day;
}
/*
* 判断是否是闰年
* 4年一闰，百年不闰，400年又闰
*/
private void isRunYear(){
if((this.year%4==0&&this.year%100!=0)||this.year%400==0){
//闰年
months[1]=29;
}else{
//平年
months[1]=28;
}
}
/*
* 天数计算
*/
public int totleDays(){
isRunYear();
int totle = 0;
for(int i=0;i
totle = totle+months[i];
}
totle =totle+this.day;
}
/*
* 判断用户输入是否存在
*/
public void isExits(){
if(month<0||month>12){
System.out.println("月份错误");
System.exit(0);
}
if(day<0||day>31){
System.out.println("日期错误");
System.exit(0);
}
}
}

展开全文
• Java 语言的Calendar(日历),Date(日期)，和DateFormat(日期格式)组成了Java标准的一个基本但是非常重要的部分。...下面这篇文章就给大家介绍了如何利用Java中Calendar计算两个日期之间的天数和周数，下面来一起看看吧。
• I know there are lots of questions on SO about how to get, but I want and example using new Java 8 Date api. I also know JodaTime library, but I want a work way without external libraries.Function nee...


I know there are lots of questions on SO about how to get, but I want and example using new Java 8 Date api. I also know JodaTime library, but I want a work way without external libraries.
Function needs to complain with these restrictions:
Prevent errors from date savetime
Input are two Date's objects (without time, I know localdatetime, but I need to do with date instances)
解决方案
If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document (and other documents re:Java 8 from Oracle).

展开全文
• public class DatePactice {public static void main(String[] args) throws ParseException {Scanner ...//计算一个人出生到现在一共多少天System.out.println("请输入你的出生日期，格式yyyy-MM-dd");String stri...

public class DatePactice {
public static void main(String[] args) throws ParseException {
Scanner scanner=new Scanner(System.in);//计算一个人出生到现在一共多少天
System.out.println("请输入你的出生日期，格式yyyy-MM-dd");
String string=scanner.next();//按格式输入时间
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");//指定格式时间转换
Date date=simpleDateFormat.parse(string);//转换成日期
long datetime=date.getTime();//时间转换成毫秒值
long todaytime=new Date().getTime();//获取当前日期毫秒值
long Difference=todaytime-datetime;//差值
System.out.println(Difference/1000/60/60/24);
}
原文：https://www.cnblogs.com/mlovx/p/13344147.html

展开全文
• Java计算两个日期间的天数，大致有2种方法：一是使用原生JDK进行计算，在JDK8中提供了更为直接和完善的方法；二是使用第三方库。1、使用原生的JDKprivatestaticlongdaysBetween(Dateone,Datetwo){longdifference...

在Java中计算两个日期间的天数，大致有2种方法：一是使用原生JDK进行计算，在JDK8中提供了更为直接和完善的方法；二是使用第三方库。
1、使用原生的JDK
private static long daysBetween(Date one, Date two) {
long difference =  (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
private static long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
这种方式由于计算简单，为广大开发人员所采用。
注意：由于转换成毫秒数计算，如果要获得较为准确的结果，应将日期规整，即将日期的时分秒设置为0:00点整点，避免2日期时间(时分秒)的差异造成计算偏差。
参考代码：
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
private int getTermDays2() throws Exception{
String sEndDate = "2018-03-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = sdf.parse(sEndDate);
long days = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days:" + days + ",yushu:" + yushu);
//规整方法1
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
long days2 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu2 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days2:" + days2 + ",yushu2:" + yushu2);
//规整方法2
String sdate1 = sdf.format(date1);
date1 = sdf.parse(sdate1);
long days3 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu3 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days3:" + days3 + ",yushu3:" + yushu3);
return (int)days;
}
public static void main(String[] args) {
DateTest dt = new DateTest();
try {
dt.getTermDays2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
private int getTermDays2() throws Exception{
String sEndDate = "2018-03-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = sdf.parse(sEndDate);
long days = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days:" + days + ",yushu:" + yushu);
//规整方法1
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
long days2 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu2 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days2:" + days2 + ",yushu2:" + yushu2);
//规整方法2
String sdate1 = sdf.format(date1);
date1 = sdf.parse(sdate1);
long days3 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
long yushu3 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
System.out.println("days3:" + days3 + ",yushu3:" + yushu3);
return (int)days;
}
public static void main(String[] args) {
DateTest dt = new DateTest();
try {
dt.getTermDays2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
规整方法1无法消除毫秒数的影响，结果差1天；规整方法1则可较好地消除时间对天数计算的影响。
因此，计算2个日期间的差别时，若不希望计算时间差异，只计算天数，则一定要先对2个日期进行规整处理，然后再进行计算，否则得到的结果可能会有较大的误差。
2、使用第三方库
使用较多的类库为jodo-time。
参考：
If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g.java.util.Date andjava.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find  the number of days between today and any date entered by a user using Joda, as well as without using any third party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can convert Date to milliseconds then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about real world date and time nuisance like leap seconds, leap years, and daylight saving time.It's very difficult to accurately calculate the difference between two dates in Java without using third party library unless you have time to develop your own library like Joda, which diligently takes these things into consideration. Thankfully, you don't need to worry because Java 8 got lucky third time.There is a new Date and Time API which has corrected previous mistakes and turns out to be a real gem. If you are keen to learn Java 8, not just this API, I suggest you grab a copy of Java 8 in Action, one of the better books to learn new features of Java 8 in quick time.
How to find number of days between two dates in Java
Since java.util.Date class implementsComparable interface it's easy to figure out whether a date come before or after another date, or whether two dates are equal to each other as shownhere, but when it comes tofinding out how many days between two dates? we don't have a simple method likedaysBetween(date1, date2) in JDK library.
Unfortunately, this is a quite common requirement, as you may need to find days between today and your next birthday, or how many days to your next insurance premium from today, or simply how many days between last two cricket world cups. In fact, calculating date and time difference is the most common date arithmetic in Java.In this article, we will see two ways to solve this problem, first by using JDK, without using any third party library and second by using the joda-time library.
How to find the difference between two dates in Java?
Though all is not lost, you can quickly write a simple routine to find the difference between two dates in terms of days in Java. How? By converting a date to milliseconds. Once you have milliseconds, you can just subtract them and then again divide them by86400000 (milliseconds per day). This way you will get exactly how many days between two dates in Java. How will you get millisecond from a date in Java? by usinggetTime() method ofjava.util.Date class, as shown below :
private static long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
This will work 99% of the time, but just like any quick and dirty solution, it will not handle any special cases e.g. time or timezone, leap years, or day light saving time. It will fail on summer boundaries when day light changes occur.
A better solution is to use a tried and tested date and time library like Joda-Time, which handles those tricky scenarios much better. Alternatively, you can also use newjava.time classes from Java 8, which are heavily influenced from the joda-time library. SeeJava SE 8 for Really Impatient by Cay S. Horstmann for more details.
BTW, if you are using JDK 8 then you and use java.time.Period class to calculate the difference between two dates in Java. Here is an example ofcalculating the date and time difference in Java 8, it's super easy and not error prone like earlier API. There is another class called,java.time.Duration, which is good to calculate a time difference between two instant.
How to calculate days between two dates using joda-time in Java?
In order to solve this problem using joda-time, we need to use a class called LocalDate to represent your dates. It is similar to LocalDate class of Java 8, or should I say LocalDate is inspired by this class.  This class knows about the weirdness we just talked about, e.g. some timezones don't have days that start at midnight. You can calculate difference between two dates in joda by using static utility class Days, which has method daysBetween() to return the number of days between two given dates as shown in the following example :
public static int daysBetweenUsingJoda(Date d1, Date d2){
return Days.daysBetween(
new LocalDate(d1.getTime()),
new LocalDate(d2.getTime())).getDays();
}
You can see that Days.daysBetween() method accepts a LocalDate and its's very easy to convert an instance of java.util.Date to org.joda.time.LocalDate class, just pass a number of milliseconds to it.
Dependency for Joda Time library Joda-Time requires Java SE 5 or later and has no dependencies. There is a compile-time dependency on Joda-Convert, but this is not required at run-time thanks to the magic of annotations. You can downloadjoda-time-2.5.jar either from Maven central or directly from http://www.joda.org/joda-time/ website. If you are using Maven then you can also add the following dependency into your pom.xml file :
joda-time
joda-time
2.5
If you download JAR file then make sure you add joda-time-2.5.jar in your Java program's classpath and you are done.  If you are not sure how to do that, see thistutorial.
Difference between two dates in number of Days
Here is our full Java program to find out how many days between two dates in Java using standard JDK classes and by using open source Joda Time library. I have name aptly named our program "date diff", as its calculating difference between dates.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import org.joda.time.Days;
import org.joda.time.LocalDate;
/**
* Java Program to find number of days between two dates in Java.
* This program calculate difference between two dates in days using two ways
* without using third party library and by using joda-time library.
*
* @author WINDOWS 8
*/
public class DateDiffExample {
private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
public static void main(String args[]) throws ParseException{
System.out.println("Please enter two dates in format yyyy/MM/dd to compare");
Date one = getDate(first);
Date two = getDate(second);
// quick and dirty way, work but not in all conditions
// you can convert date into milliseconds then subtract
// them and again convert it to days
long numberOfDays = daysBetween(one, two);
System.out.printf("Number of days between date %s and %s is : %d %n",
first, second, numberOfDays);
// a better way to calculate difference between two dates in Java
// is by using JodaTime library as shown below
int differenceBetweenDates = daysBetweenUsingJoda(one, two);
System.out.printf("difference betweeen two dates %s and %s is : %d %n",
first, second, differenceBetweenDates);
}
/*
* Simple way to parse String to date in Java
*/
private static Date getDate(String date) throws ParseException{
return df.parse(date);
}
/*
* Java Method to calculate difference between two dates in Java
* without using any third party library.
*/
private static long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
/*
* Java Method to find number of days between two dates
* in Java using JodaTime library. To find difference
* we first need to convert java.util.Date to LocalDate
* in JodaTime.
*/
public static int daysBetweenUsingJoda(Date d1, Date d2){
return Days.daysBetween(
new LocalDate(d1.getTime()),
new LocalDate(d2.getTime())).getDays();
}
}
Output:
Please enter two dates in format yyyy/MM/dd to compare
2014/11/23
2014/11/25
Number of days between date 2014/11/23 and 2014/11/25 is : 2
difference between two dates 2014/11/23 and 2014/11/25 is : 2
You can see that number of days between two dates are correct and output of both our own method and joda-time is same.

展开全文
• java实现输入任意两个日期输出月份数和天数，综合考虑闰年、2月等因素，对于整月计算利息或按天数计算利息提供基础工具类。也可以吧内部类独立出来，方便跨包调用，可自行调整。很实用的一个实现。其他百度查到的很...
• 展开全部import java.util.Scanner;/*** Created by xpf on 2018/6/22 :)* GitHub:xinpengfei520* Function:*/public class CalculateUtils {/*平年二月28天*/private static final int DAYS_28 = 28;/*闰年二月29天...
• import java.time.LocalDate;/*** 计算两个日期之间的天数** @author 枫茗丿love*/public class CountDaysUtils {/*** 两个日期之间的天数** @param start* @param end* @return*/public static int betweenDay...
• 这个工具类是计算两个时间相差多少天的工具类以及格式化时间
• * 计算开始时间，结束时间，间隔天数 * @param startDate * @param endDate * @return * @throws ParseException */ public static int getDayDiffer(Date startDate, Date endDate) throws ParseException {...
• 文章来源: http://www.jb51.net/article/75551.htm这篇文章主要介绍了java计算两个时间相差天数的方法，感兴趣的小伙伴们可以参考一下:问题描述：输入：两个日期输出：两个日期相差的天数具体代码实现方法1：通过...
• java获取日期之间天数的方法本文实例讲述了java获取日期之间天数的方法。分享给大家供大家参考。具体实现方法如下：private int daysBetween(Date now, Date returnDate) {Calendar cNow = Calendar.getInstance();...
• 确定是闰年还是平年之后，用输入日期加上已经经历过的天数，就是这一年的第几天。如：以3月5日为例，应该先把前两个月的总天数加起来，然后再加上5天即本年的第几天，特殊情况，闰年且输入月份大于3时需考虑多加一天...
• 当我们需要计算两个日期相差的天数怎么办呢，今天我们就来用 Java 比较两个日期相差的天数，最简单的方法，直接上代码：第一种，Date类型计算publicstaticintdifferentDaysByDate(Datedate1,Datedate2){intdays=(int...
• //结果将会 两个日期间隔天数 是5天 Long tempString = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24); obj=String.valueOf(tempString); } } return obj; }
• 输入： 2012 12 31 输出： 366 以下是本篇文章正文内容，下面案例可供参考 解题思路 先将每月的天数保存到一个数组中 若年份为闰年，则将二月的天数+1 计算给的月份之前的天数，最后再加上给的天数 代码如下 import ...
• 有一种low的方式，就是你把两个时间都换成秒，然后除以一天的秒数，然后向上取整，就是天数。但是这么实现太low啦。jdk有高级的API，我们为啥还要自己去实现呢，问题就是我们不知道。所以，我在这写个笔记，记录...
• 要求：计算1999年1月1日和2018年11月3日相差多少天 思路： 1、每年的天数累加，需判断闰年、平年 2、每月的天数累加，不同月份天数不同，平年和闰年，2月份... * 计算两个日期之间相差的天数 * 如：计算1999年1月1...
• 回答完毕，5天即可import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class YuGiOh{public static int getDay1 ( String starttime, String endtime ){Date start =...
• 我想要一个Java程序来计算两个日期之间的天数。键入第一个日期(德语表示法；带空格：“ dd mm yyyy”)输入第二个日期。该程序应计算两个日期之间的天数。如何包含include年和夏季？我的代码：import java.util....
• * 计算两个日期间隔天数 * * @param startTime ： 开始时间 * @param endTime ： 结束时间 * @return */ public static int caculateTotalTime(String startTime, String endTime) { Si...
• 随机输入日期计算星期几，打印任意一年的日历 已知，1900年1月1日是星期1，用户随机输入年月日，计算星期几 实现思路： 一、知道1900年1月1日为星期一，求输入的年份月份与1900年1月1日相隔的总天数。闰年366天，...
• package ...import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class CompareTime {public...
• 目的：获取当前时间前n天的日期 (示例就以30天为例)运行代码：返回的类型 java.sql.Datelong time = 30*86400000;SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");String format = ...
• Java8新增了java.time包，提供...其中LocalDate正是本文中使用的可以帮助计算两个日期的间隔天数的类。(其它常用的还有LocalTime, Clock, Instant等，本文不赘述)话不多说，上代码！LocalDate day0 = LocalDate.of(2...
• 求两个日期之间相差的天数 利用日期类将用户输入的两个日期字符串转换成为日期格式，用相应日期类操作方法将两个日期之间相差天数计算出来。
• java输入日期计算星座[2021-01-31 12:59:06]简介:php去除nbsp的方法：首先创建一个PHP代码示例文件；然后通过“preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags(\$val));”方法去除所有nbsp即可。...
• 根据输入日期计算是这一年的第几天。 输入描述: 输入一行，每行空格分割，分别是年，月，日 输出描述: 输出是这一年的第几天 示例： 输入 2012 12 31 输出 366 输入 1982 3 4 输出 63 代码示例： ...

...

java 订阅