2

i have a really simple problem, i don't know how to deduct the user's date by 01/01 / (the user year) +1. Im really stuck at this point.

public static void main(String[] args)
{
    String date;
    Scanner teclado = new Scanner (System.in);
    System.out.println("Dame una fecha formato dd/mm/yyyy");
    date=teclado.next();
    Date mydate =FinalAnio.ParseFecha(date);    
    System.out.println(mydate);
    
    
}

 public static Date ParseFecha(String fecha)
    {
        SimpleDateFormat formato = new SimpleDateFormat("dd/mm/yyyy");
        Date fechaDate = null;
        try 
        {
            fechaDate = formato.parse(fecha);
        } 
        catch (ParseException ex) 
        {
            System.out.println(ex);
        }
        return fechaDate;
    }
Semicolon
  • 127
  • 5
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). They are also much better suited for the job. – Ole V.V. Dec 02 '20 at 20:36
  • No matter if using the modern `DateTimeFormatter` or the outdated `SimpleDateFormat`, beware of the case of format pattern letters. Lower case `mm` means something else than upper case `MM`, and so forth. – Ole V.V. Dec 02 '20 at 20:38
  • Does this answer your question? [Calculate days between two dates in Java 8](https://stackoverflow.com/questions/27005861/calculate-days-between-two-dates-in-java-8) – Ole V.V. Dec 02 '20 at 20:41

2 Answers2

2
  1. The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

  2. Do not use mm for the month as it is used for the minute. For the month, the correct symbol is MM. Check DateTimeFormatter to learn more about various symbols used for parsing/formatting string/date-time.

  3. Learn about the calculations of the period and duration from Period and Duration tutorial from Oracle. It would also be worth going through this Wikipedia page on Durations.

Demo:

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter date in the format dd/MM/yyyy: ");
        String strDate = scanner.next();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
        LocalDate userDate = LocalDate.parse(strDate, dtf);

        // The date representing 01/01/(the user year)+1
        LocalDate targetDate = userDate.withDayOfMonth(1).withMonth(1).plusYears(1);

        System.out.println("User's date: " + strDate);
        System.out.println("Target date: " + targetDate.format(dtf));

        Period period = Period.between(userDate, targetDate);
        System.out.printf("Difference: %d days %d months %d years%n", period.getDays(), period.getMonths(),
                period.getYears());

        System.out.println("The difference in terms of days: " + ChronoUnit.DAYS.between(userDate, targetDate));
    }
}

A sample run:

Enter date in the format dd/MM/yyyy: 20/10/2015
User's date: 20/10/2015
Target date: 01/01/2016
Difference: 12 days 2 months 0 years
The difference in terms of days: 73

Learn about the modern date-time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

java.time

I recommend that you use java.time, the modern Java date and time API, for your date work.

    DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    String entradaUsuario = "02/12/2020";
    LocalDate fecha = LocalDate.parse(entradaUsuario, formatador);
    LocalDate finDeAño = fecha.with(MonthDay.of(Month.DECEMBER, 31));
    long diasRestantes = ChronoUnit.DAYS.between(fecha, finDeAño);
    System.out.println(diasRestantes);

Output is:

29

In the format pattern string upper case MM is for month of year (lower case mm would be minute of hour, so not useful here). uuuu is for year (yyyy would work too).

fecha.with(MonthDay.of(Month.DECEMBER, 31)) adjusts the date to December 31 in the same year.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Dude, thanks a lot, you save me, im tried a thousand differents forms debofre and doesntt work, with this works perfect, many thanks!. – Semicolon Dec 02 '20 at 21:13