This question already has answers here:
Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?
(6 answers)
Closed 6 years ago.
I try to convert string to date on java. I read and try the example from this website "Java Date and Calendar examples" but I still cannot compile and run it.
This is my code.
package javaapplication5;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class JavaApplication5 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(date);
}
}
And I got this error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.text.ParseException; must be caught or declared to be thrown
What I missing or do it wrong? Thank you for help.
The problem is that java.text.ParseException is checked exception
A checked exception is a type of exception that must be either caught or declared in the method in which it is thrown
So... You might declare it in throws list
public static void main(String[] args) throws ParseException {
/* ... */
}
Or should properly handle it it
public static void main(String[] args) {
try {
Date date = sdf.parse(dateInString);
} catch (ParseException e) {
// do proper thing here like try another
// format or log/rethrow/wrap exception
}
}
Try to put all your code in a try/ catch block
try{
// your code here.
}catch(Exception e){
e.printStackTrace();
}
Just add your code in try catch block.
try {
//parse code
}
catch (ParseException e) {
//handling exceptions
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = null;
try {
date = sdf.parse(dateInString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date);
Add a try-catch block like this:
try
{
//...Code.... Mainly below:
Date date = sdf.parse(dateInString);
} catch (ParseException e)
//Or any superclass, such as RuntimeException,
//although use superclass ONLY to be generic, not otherwise, such as
//if you want to handle all exceptions the same way.
{
//...Handler Code...
}
Related
I am getting a unreported exception ParseExpcetion error trying to convert Date. Here is my code that is getting the error, I believe I have to use a try and catch block, but I am unsure of how to use it here.
import javax.swing.JOptionPane;
import java.util.Date;
import java.text.*;
public class JOptionQuestionTen
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Insert Date in Form MM/dd/yy");
DateFormat inputFormat = new SimpleDateFormat("MM/dd/yy");
DateFormat outputFormat = new SimpleDateFormat("dd.MM.yy");
Date date = inputFormat.parse(input);
String formattedDate = outputFormat.format(date);
JOptionPane.showMessageDialog(null, formattedDate);
}
}
You need to catch the exception, and hopefully provide a different output message. E.g.:
String output;
try {
Date date = inputFormat.parse(input);
output = outputFormat.format(date);
} catch (ParseException e) {
output = "Can't parse input of " + input;
// also probably a log.error(e)
}
JOptionPane.showMessageDialog(null, output);
You forgot to catch the exception that is thrown. Wrap the code that throws the exception (a good IDE helps here) in a try-catch like this:
DateFormat inputFormat = new SimpleDateFormat("MM/dd/yy");
DateFormat outputFormat = new SimpleDateFormat("dd.MM.yy");
try{
Date date = inputFormat.parse(input);
String formattedDate = outputFormat.format(date);
}
catch(ParseException ex){
//Do something
}
Hi i am truing to convert this string 2015-11-26 to Date object so:
I am trying this:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date result=null;
try {
result = df.parse(date);
} catch (ParseException ex) {
Logger.getLogger(XmlReaderDemo.class.getName()).log(Level.SEVERE, null, ex);
}
codecurrency.setDate(result);
And date is the string holding 2015-11-26
It gives me exception and I don't know why.
Your code is working fine:
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.*;
import java.text.ParseException;
public class DateExample {
public static void main (String args[]) {
String date = "2015-11-26";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date result = null;
try {
result = df.parse(date);
} catch (ParseException ex) {
ex.printStackTrace();
}
System.out.println("result: " + result);
}
}
I just changed it a bit, so it compiles.
If you still can't get it to work, please post a Runnable example so we can provide more and better help.
This is the output I get:
result: Thu Nov 26 00:00:00 CST 2015
Also looking at the exception and your code, you probably want to move this line:
codecurrency.setDate(result);
inside the try call...
So I am having this issue that I can't wrap my head around. I've read similar questions posed but very case I've found there is an issue with the format, and my format is correct.
Basically I am trying to convert a String into a Timestamp, and I get the unparseable date error.
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {
public static Timestamp convertStringToTimestamp(String str_date) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
System.out.println(ts +" | "+ts2);
}
}
Output:
Exception :java.text.ParseException: Unparseable date: "2015-06-09 11:51:12,708"
Exception :java.text.ParseException: Unparseable date: "2015-04-17 11:29:49.564"
null | null
Any ideas?
This works perfectly to me.
I just passed the right pattern as an input as well.
public static Timestamp convertStringToTimestamp(String str_date, String pattern) {
try {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708", "yyyy-MM-dd HH:mm:ss,SSS");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564", "yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(ts +" | "+ts2);
}
The output is:
2015-06-09 11:51:12.708 | 2015-04-17 11:29:49.564
"2015-06-09 11:51:12,708" is working for me but "2015-04-17 11:29:49.564" won't. You specified the regex for "," so "." would not. It is perfectly normal.
you need to fix the comma
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
**Update**
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SomeClass {
public static void main(String[] args) {
System.out.println(convertStringToTimestamp("2015-06-09 11:51:12,708"));
//be consistent here with , and .
System.out.println(convertStringToTimestamp("2015-04-17 11:29:49.564"));
System.out.println();
}
private static Timestamp convertStringToTimestamp(String something) {
SimpleDateFormat dateFormat = null;
if(something.contains(".")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
}
if(something.contains(",")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
}
Timestamp timestamp = null;
Date parsedDate;
try {
parsedDate = dateFormat.parse(something);
timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timestamp;
}
}
I am getting an error( Unparseable date: "18–11–2003") when i try to import data from excel file. the date from the file cannot be parsed
if(row.getCell(16)!=null){
String dobb=null;
Date dob=null;
row.getCell(16).setCellType(row.getCell(16).CELL_TYPE_STRING);
dobb=row.getCell(16).getStringCellValue();
System.out.println(dobb);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
dob = (Date)simpleDateFormat.parse(dobb);//error..... Unparseable date: "18–11–2003"
System.out.println("dateeee"+dob);
} catch (ParseException e) {
e.printStackTrace();
//dob=new Date();
}
It looks like the specified "18–11–2003" date contains u2013 Unicode character instead of a normal dash which is u002d.
Here is a sample that uses the string copy-pasted from the question:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
String trouble = "18–11–2003";
String goodOne = "18-11-2003";
Date date = simpleDateFormat.parse(goodOne);
//Date date = simpleDateFormat.parse(trouble);
System.out.println(String.format ("\\u%04x", (int)trouble.charAt(2)));
System.out.println(String.format ("\\u%04x", (int)goodOne.charAt(2)));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The character in the actual date (–) is not the same character in your date format (-).
This code:
public static void main(String[] args) {
System.out.println((int)'–');
System.out.println((int)'-');
}
produces this result:
8211
45
There are several things you can do:
Do a replace() on your date string (dateStr = dateStr.replace("–", "-");) to replace the strange hyphen with an actual ASCII hyphen. *Recommended*
Change your dateformat from "dd–MM–yyyy" to "dd–MM–yyyy"
This question already has answers here:
Parsing error for date field
(2 answers)
Closed 8 years ago.
Is it possible to convert string "20110210"
to a java.sql.Date 2011-02-10?
I've tried SimpleDateFormat and I get java.text.ParseException: Unparseable date: "20110210"
What am I doing wrong?
i had
new SimpleDateFormat("yyyy-MM-dd")
instead of
new SimpleDateFormat("yyyyMMdd")
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());