Home > Enterprise >  Exception in thread "main" java.text.ParseException: Unparseable date:-Trying to get finan
Exception in thread "main" java.text.ParseException: Unparseable date:-Trying to get finan

Time:04-27

public class Practice_GetFinancialyYear {

public static void main(String[] args) throws ParseException {
    Scanner myObj = new Scanner(System.in); // Create a Scanner object
    System.out.println("Enter Date:");

    String sdate = myObj.next();
    SimpleDateFormat formatDate=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
    Date actualDate=formatDate.parse(sdate);
    SimpleDateFormat formatDate2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
    System.out.println(formatDate2.format(actualDate));
    
    int year = GetCurrentFinanicial(actualDate);
    System.out.println("Financial Year : "   year   "-"   (year   1));

}

public static int GetCurrentFinanicial(Date date) {

    int result = -1;
    if (date != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        result = cal.get(Calendar.YEAR);
    }
    return result;

}

}

//Entering input string as 2011-01-18 00:00:00.0 //But still I am facing same Unparseable date.

CodePudding user response:

The error is on the date format that you are trying to parse your input.

It should be:

SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

instead of:

SimpleDateFormat formatDate=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");

CodePudding user response:

public class Practice_GetDateTime {

public static void main(String[] args) throws ParseException {
    
    String pattern = "yyyy-MM-dd HH:mm:ss.S";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    
    try {
        
      Scanner sc = new Scanner(System.in); // Create a Scanner object
      System.out.println("Enter Date:");
      String sdate = sc.nextLine();         
      Date date = format.parse(sdate);
      System.out.println(date);
              
      int year = GetCurrentFinanicial(date);
    System.out.println("Financial Year : "   year   "-"   (year   1));
      
    } catch (ParseException e) {
      e.printStackTrace();
    }       
    
}

public static int GetCurrentFinanicial(Date date) {

    int result = -1;
    if (date != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        result = cal.get(Calendar.YEAR);
    }
    return result;

}

}

//This way it helped me to solve the Unparseable date exception. This is the correct way to write the date format.

  • Related