-3

I am trying to input the date from the user. But the code is giving error at the parse method. The code I am trying is below.

import java.util.*;
import java.text.SimpleDateFormat;

public class date_parse {
    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        String s=input.nextLine();
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(f.parse(s));
    }   
}

NOTE -: The code is running well if I directly provide string format date like "01-01-2000" in place os s in parse method

smac89
  • 39,374
  • 15
  • 132
  • 179
Arpit
  • 394
  • 1
  • 11

2 Answers2

2

First of all you don't name your class like that in Java. Please go through this article to know more about naming conventions in Java. Secondly as Risalat Zaman mentioned the parse method throws ParseException which need to be handled in your code. Try changing your code as follows:

public class DateParse {
    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        String s=input.nextLine();
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        try {
            System.out.println(f.parse(s));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
rakesh
  • 216
  • 1
  • 7
1

Try it like this

    try{
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(f.parse(s));     
    }
    catch(Exception e){
        System.out.print("There is an exception");
    }
Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19
  • It’s not a god answer IMHO. First helping people use `SImpleDateFormat`, a class that we should no longer use, is doing a mis-favour. Second, the code works (I think), but the answer does not explain why. Third catching `Exception` is bad style and also not helpful in explaining why it’s being done. – Ole V.V. Feb 07 '21 at 19:09
  • Could you enlighten me as to why we should not use SimpleDateFormat please – Risalat Zaman Feb 08 '21 at 12:53
  • 1
    Thanks for asking. Oracle says: [Why do we need a new date and time library?](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html) Others say: [Still using java.util.Date? Don’t!](https://programminghints.com/2017/05/still-using-java-util-date-dont/) and [What's wrong with Java Date & Time API? \[closed\]](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api) – Ole V.V. Feb 08 '21 at 20:05