-2

I'm new to Java, I'm getting an exception when I try to convert string to simple date format.

Scanner input = new Scanner(System.in);
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");

System.out.print("Time period (DD/MM/YYYY): ");
String sTime = input.nextLine();

Date time = dateFormat.parse(sTime);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    What's the exception? And what's the input? – EJoshuaS - Stand with Ukraine Nov 08 '20 at 04:24
  • @EJoshuaS-ReinstateMonica It's a `java.text.ParseException` and String is a simple user input like `05/08/2020`. – user14598597 Nov 08 '20 at 04:27
  • 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/). – Ole V.V. Nov 08 '20 at 09:03
  • If you are getting an exception, please pate the full stack trace into your question, formatted as code for readability. And thanks for the further information. Please put that in your question too so we have everything in one place. Surprisingly many users don’t read the comments. – Ole V.V. Nov 08 '20 at 09:05
  • Also, while your code example is short, which is nice, I recommend that you shorten it further by leaving out the scanner and hardcoding the input into your code. or as suggested on [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/) “If the code performs I/O to files, replace the file I/O with dummy data structures in problems that are unrelated to input/output.” Your problem is unrelated to user input. – Ole V.V. Nov 08 '20 at 09:16

2 Answers2

0

The parse() method of DateFormat throws ParseException. Also the format has mm which shows minutes value in Date. MM shows the months value which is what you want.

Scanner input = new Scanner(System.in);
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        
        System.out.print("Time period (DD/MM/YYYY): ");
        String sTime = input.nextLine();
        
        Date time = dateFormat.parse(sTime);
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
babli1897
  • 1
  • 1
  • parse method of DateFormat throws ParseException. Also the format has "mm" which shows minutes value in Date. MM shows the months value – babli1897 Nov 08 '20 at 04:32
0

The parse method of DateFormat throws ParseException. So change the main to

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

also include the following

import java.text.ParseException;