如何在Java中获得已经过去的天数,当我输入一些随机日期?

huangapple go评论90阅读模式
英文:

How would I get the number of days completed in Java when I input some random date?

问题

public class NumberOfCompletedDays {

    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {

        Scanner scanner = new Scanner(System.in);
        String date1;
        String date2 = "00 00 0000";
        long completedDays;
        System.out.println("Enter the date");
        date1 = scanner.nextLine();
        String[] date1Array = date1.split(" ");
        String[] date2Array = date2.split(" ");
        date2Array[2] = date1Array[2];
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < date2Array.length; i++) {
            builder.append(date2Array[i]);
            builder.append(" ");
        }
        date2 = builder.toString();

        SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
        Date mydate1 = myFormat.parse(date1);
        Date mydate2 = myFormat.parse(date2);
        completedDays = mydate1.getTime() - mydate2.getTime();
        System.out.println("Days: " + TimeUnit.DAYS.convert(completedDays,
                TimeUnit.MILLISECONDS));

    }

}
英文:

How would I get the number of days completed in Java when I input some random date(dd/mm/yyyy). For example , if my input is 15 1 2020 I need to get 15 as output.

Here is my code.



public class NumberOfCompletedDays {

	/**
	 * @param args
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
				
		Scanner scanner = new Scanner(System.in);
		String date1;
		String date2 = &quot;00 00 0000&quot;;
		long completedDays;
		System.out.println(&quot;Enter the date&quot;);
		date1 = scanner.nextLine();
		String[] date1Array = date1.split(&quot; &quot;);
		String[] date2Array = date2.split(&quot; &quot;);
		date2Array[2] = date1Array[2];
		StringBuilder builder = new StringBuilder();
		for(int i  = 0; i &lt; date2Array.length; i++){
			builder.append(date2Array[i]);
			builder.append(&quot; &quot;);
		}
		date2 = builder.toString();
		
		SimpleDateFormat myFormat = new SimpleDateFormat(&quot;dd MM yyyy&quot;);
		Date mydate1 = myFormat.parse(date1);
	    Date mydate2 = myFormat.parse(date2);
	    completedDays = mydate1.getTime() - mydate2.getTime();
	    System.out.println (&quot;Days: &quot; + TimeUnit.DAYS.convert(completedDays, 
        TimeUnit.MILLISECONDS));
		
	}

}

答案1

得分: 1

## java.time

在处理日期时请使用现代的 Java 日期和时间 API - java.time这样会简单得多

```java
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MM uuuu");

/** @throws DateTimeParseException if the user enters an invalid date */
public static void main(String[] args) {
    
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the date");
    String date1 = scanner.nextLine();
    LocalDate mydate1 = LocalDate.parse(date1, dateFormatter);
    long completedDays = mydate1.getDayOfYear();
    System.out.println("Days: " + completedDays);
}

示例会话:

>     Enter the date
>     15 01 2020
>     Days: 15

代码中出了什么问题?

除了过于复杂化,并且使用旧的和麻烦的日期和时间类之外,您还从第 0 个月的第 0 天开始计算天数。这显然是荒谬的,但 SimpleDateFormat 却允许您这样做。第 0 个月是第 1 个月之前的月份,因此是上一年的十二月。而每月的第 0 天是第 1 天之前的一天,即 11 月 30 日。例如,从 11 月 30 日到 1 月 15 日的天数是 46 天,这可能是您得到的结果。

我说可能是因为像您所做的从毫秒转换为天数,并不总是给出正确和预期的结果。这种转换假设一天始终是 24 小时,但实际情况并非总是如此。夏令时(DST)和其他时间异常有时会导致一天变长或变短。如果用户在北半球的春季间隙夏时制开始之后(但在秋时制结束之前)输入日期,则转换毫秒将导致少一天的结果,例如。

链接

Oracle 教程:日期时间,解释了如何使用 java.time。


<details>
<summary>英文:</summary>

## java.time

Do use java.time, the modern Java date and time API, for your date work. Then it’s much simpler:

	static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(&quot;dd MM uuuu&quot;);

	/** @throws DateTimeParseException if the user enters an invalid date */
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
	    System.out.println(&quot;Enter the date&quot;);
	    String date1 = scanner.nextLine();
	    LocalDate mydate1 = LocalDate.parse(date1, dateFormatter);
	    long completedDays = mydate1.getDayOfYear();
	    System.out.println (&quot;Days: &quot; + completedDays);
	}

Example session:

&gt;     Enter the date
&gt;     15 01 2020
&gt;     Days: 15

## What went wrong in your code?

Apart from over-complicating things and using old and troublesome date and time classes you were counting days from the 0th day of the 0th month. This is clearly nonsense, but `SimpleDateFormat` lets you get away with it. The 0th month is the month before the 1st month, so December of the previous year. And the 0th day of the month is the day before the 1st, so 30th November. The count of days from November 30 to January 15 is 46, for example, the result that you probably got.

I say *probably* because converting from milliseconds to days, like you did, does not always give the correct and expected result. This conversion assumes that a day is always 24 hours, which it isn’t always. Summer time (DST) and other time anomalies cause a day to be longer or shorter sometimes. If the user enters a date after the *spring gap* or *spring forward* on the Northern hemisphere (but before the *fall back*), converting the milliseconds will result in one day too few, for example.

## Link

[Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.


</details>



# 答案2
**得分**: 0

```python
如果您询问如何找到两个日期之间的差异:

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
    Date firstDate = sdf.parse("06/24/2017");
    Date secondDate = sdf.parse("06/30/2017");
 
    long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
    long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
英文:

If you are asking about finding difference between two days:

SimpleDateFormat sdf = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;, Locale.ENGLISH);
Date firstDate = sdf.parse(&quot;06/24/2017&quot;);
Date secondDate = sdf.parse(&quot;06/30/2017&quot;);

long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

huangapple
  • 本文由 发表于 2020年4月4日 18:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61026785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定