-3

Can you help me debug?

Parse won't convert my date to string. Here's my whole code

String newDate = "05252021";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date today1 = new Date();
String dateToday = sdf.format(today1);

System.out.println("Date Now : " + dateToday);

int betweenDays = 0;
Date hireDate= sdf.parse(newDate); // error sdf.partse
long  between = today1.getTime() - hireDate.getTime();
betweenDays = (int) (between / (24 * 60 * 60 * 1000));

Error encountered

Unhandled exception: java.text.ParseException

java.text.DateFormat public java.util.Date parse(String source) throws java.text.ParseException
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string. See the parse(String, ParsePosition) method for more information on date parsing.
Params: source – A String whose beginning should be parsed.
Returns: A Date parsed from the string.
Throws: java.text.ParseException – if the beginning of the specified string cannot be parsed

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    `sdf` has slashes separating months, days and years. `newDate` doesn't. – shmosel Jun 30 '21 at 05:25
  • Make newDate `05/25/2021` – OhhhThatVarun Jun 30 '21 at 05:26
  • i did try that same error – Vida Vida Jun 30 '21 at 05:29
  • 4
    Please, stop using `Date` and `SimpleDateFormat`, they're obsolete. Use classes from the `java.time` package. – MC Emperor Jun 30 '21 at 05:32
  • Works fine for me: https://ideone.com/bE6kOi – shmosel Jun 30 '21 at 05:33
  • thanks oh did not try this one throws java.lang.Exception now its working thanks for the tips im still not familiar on the whole code thanks alot ^^ – Vida Vida Jun 30 '21 at 05:44
  • 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) – Abra Jun 30 '21 at 06:14
  • _`Unhandled exception: java.text.ParseException`_ Your IDE is telling you that your code needs to handle `ParseException` that may be thrown by method `parse` in class `java.text.DateFormat` (which is the superclass of `SimpleDateFormat`). – Abra Jun 30 '21 at 06:21

2 Answers2

1

Formatting pattern must match input

Your formatting pattern "MM/dd/yyyy" does not match your input "05252021".

java.time

Also, you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. For a date-only value without a time-of-day and without the context of a time zone or offset-from-UTC, use java.time.LocalDate.

String input = "05252021" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMdduuuu" ) ;
LocalDate then = LocalDate.parse( input , formatter ) ;

Tip: Educate the publisher of your data about using ISO 8601 standard formats for communicating date-time values textually.

To represent elapsed time as a number of years-months-days, use Period.

LocalDate today = LocalDate.now( ZoneId.of( "America/Edmonton" ) ) ;
Period p = Period.between( then , today ) ;

Or, if you just want a count of days elapsed:

java.time.temporal.ChronoUnit.DAYS.between( then , today )

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

In the method where this is defined throw an exception like throws ParseException. Also, use format your string like String newDate = "05/25/2021".

You can also use a try catch block around the Date hireDate = sdf.parse(newDate); to catch any exceptions. Ex given below:

1: public static void main(String[] args) throws ParseException {

    String newDate = "05/25/2021";
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date today1 = new Date();
    String dateToday = sdf.format(today1);
    System.out.println("Date Now : " + dateToday);

    int betweenDays = 0;
    Date hireDate= sdf.parse(newDate);
    System.out.println("Date Now : " + hireDate);
    long  between = today1.getTime() - hireDate.getTime();
    betweenDays = (int) (between / (24 * 60 * 60 * 1000));

}
  • Are you suggesting to change the input to "05/25/2021"? OP may or may not be able to control input. Should OP change his code to throw a `ParseException`? Why would OP wrap the parsing code with a `try` block? What would he do with the caught exception? Please check [answer]. – Robert Jun 30 '21 at 22:44
  • Hi Robert, noted . I suggested him to change his input since the SimpleDataFormat he has initialise is in the format MM/DD/YYYY . Will try to improve the details and explanation . – vivek chandra Jul 01 '21 at 10:54