Java: convert birth data to days

后端 未结 4 519
春和景丽
春和景丽 2021-01-17 06:11

I really need some help with the specific assignment. The user inputs birth data (YYYY MM DD) and the program tells you how old you are in days :

The outprint in co

相关标签:
4条回答
  • 2021-01-17 06:48

    Use the DateFormat class which you can utilize the .parse() on the input. Which gives you a Date class which then has .getTime() which returns the number of milliseconds. Then create a new Date class and subtract the .getTime() milliseconds. Convert to Days.

    Date birth = DateFormat.parse(inputString);
    Date now = new Date();
    long diff = now.getTime() - now.getTime();
    int days = ((((diff / 1000) / 60) / 60) / 24)
    

    EDIT: According to the code you listed below, you should just be able to do

    Scanner input=new Scanner(System.in);
    System.out.print ("Enter birth date (yyyy/mm/dd): ");
    String yourBirthDay=input.nextLine();
    Date birth = DateFormat.parse(yourBirthDay);
    Date now = new Date();
    long diff = now.getTime() - now.getTime();
    int days = ((((diff / 1000) / 60) / 60) / 24)
    
    0 讨论(0)
  • 2021-01-17 06:58

    java.time

    In Java 8 and later, you could use the java.time classes such as ChronoUnit and LocalDate. Perhaps not appropriate to a homework assignment though.

    long days = ChronoUnit.DAYS.between( LocalDate.parse( "1981-11-06" ) , LocalDate.now( ZoneId.of( "America/Montreal" ) ) ) ;
    
    0 讨论(0)
  • 2021-01-17 07:00

    Have you considered the Calendar class? It has functions for parsing dates from strings and comparing them.

    0 讨论(0)
  • 2021-01-17 07:13

    Well, when I imported the needed class, it worked just fine:

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    

    The error Eclipse gave you is probably because you didn't import the correct classes.

    A little hint: use ctrl + shift + o to add missing imports in eclipse

    0 讨论(0)
提交回复
热议问题