i was searching how to convert a string to a date, so i've found some examples on stacko. . So i used SimpleDateFormat and tried to parse but my compiler (Gradle from AndroidStudio) send me this error : Unhandled exception : java.text.ParseException.
There is my code :
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1); // there is the error
[...]
}
Why is there an error? Someone can explain that to me?
I'm a beginner in java and i'm sorry for my bad english, and i hope someone can help me on this.
Thanks
The parse method throws a ParseException. You need to insert a catch block or your method should throw ParseException in order to get rid of the error:
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
try {
Date date1 = simpleDateFormat.parse(sdate1);
} catch (ParseException e) { // Insert this block.
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OR
public static int compareDate(String sdate1, String sdate2) throws ParseException{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1);
}
Related
I'm making a GUI in java for a todo list and i want to write a todo type object in a file. A todo object has name, description and a date that determinds this to be done. With GUI a user can add as many todo objects he wants with them be written to a file. I'm having trouble getting the date from user from a JTextField using getText() and parsing it in a LocalDate type object in order to be written in the file.
Code I'm running now:
//registration method
public void RegularObligationRegister(RegularObligations R) throws IOException {
try {
objOutObligations.writeObject(R);
JOptionPane.showMessageDialog(null, "Save Success");
System.out.println(R);
objOutObligations.flush();
} catch (FileNotFoundException ex) {
System.out.println("Error with specified file . . .");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//actionperformed method
#Override
public void actionPerformed(ActionEvent ae) {
.
.
.
if (ae.getSource().equals(REntryObligationSave)) {
RegularObligations R = new RegularObligations(RegularEntry_TextObligationName.getText(),
RegularEntry_TextObligationDescription.getText(),
LocalDate.parse(RegularEntry_TextObligationDeadline.getText()));
try {
this.RegularObligationRegister(R);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
RegularEntry_TextObligationName.setText(null);
RegularEntry_TextObligationDescription.setText(null);
RegularEntry_TextObligationDeadline.setText(null);
}
You need to make sure that your text must be valid LocalDate.parse() method to parse. You need to specify your text format for the LocalDate. For ex: (dd MMM uuuu). Then you should pass your text and formatter to the LocalDate.parse() method as parameter. The example below will help you to parse a String similar to : "31 Dec 2018" as a LocalDate
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM uuuu");
LocalDate.parse(RegularEntry_TextObligationDeadline.getText(),formatter));
You can check DateTimeFormatter to customize your datetype as a text DateTimeFormatter
My SimpleDateFormat keeps throwing a ParseException. I can’t get it to actually get into the try block, it just keeps going directly to my catch. Any idea what is wrong in my code?
public static String getEventDate() throws ParseException {
System.out.println("When is the date of your event? (dd/MM/yyyy)");
String date = in.nextLine();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date eventDate = null;
try {
eventDate = dateFormat.parse(date);
} catch (ParseException e) {
System.out.println("Error in date format");
}
String finalDate = dateFormat.format(eventDate);
return finalDate;
}
public static void main(String[] args) throws ParseException {
Event event = getEventInfo();
System.out.println(event);
}
public static Event getEventInfo() throws ParseException {
String eventType = getEventType();
String eventDate = getEventDate();
Event event = new Event(eventType, eventDate);
return event;
}
I am running SonarQube 5 for code quality check after integrating the code with Maven.
Sonar is complaining that I should:
Either log or rethrow this exception.
in following piece of code:
public static Date convertStringtoDate(String stringDate) {
stringDate = StringUtils.trimToNull(stringDate);
SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
if (stringDate != null) {
try {
date = dfm.parse(stringDate);
} catch (Exception e) {
logger.info("Cannot convert String to Date: ",convertStringtoDate(e.getMessage()));
}
}
return date;
}
What am I missing here?
First of all, is this behaviour correct? Seems a bit weird that you are trying to call convertStringtoDate on the exception message as well.
Secondly, I had the same problem with Sonar recently. Seems like you need to pass the whole exception as a parameter to the logger, instead of e.getMessage() for Sonar to realize you are logging the exception.
Try this instead:
public static Date convertStringtoDate(String stringDate){
stringDate = StringUtils.trimToNull(stringDate);
SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
if(stringDate!=null){
try {
date = dfm.parse(stringDate);
} catch (Exception e) {
logger.info("Cannot convert String to Date: ", e);
}
}
return date;
}
Does somebody know if there is a online code analyser for java. I would like to be able to check some small pieces of code.
Ex: this method has this warning: (Null Dereference)
private XMLGregorianCalendar asXMLGregorianCalendar(Date data) {
DatatypeFactory dateformat = null;
try {
dateformat = DatatypeFactory.newInstance();
} catch (MyException e) {
///
}
if (data == null) {
return null;
} else {
GregorianCalendar gregorianCal = new GregorianCalendar();
gregorianCal.setTimeInMillis(data.getTime());
return dateformat.newXMLGregorianCalendar(gregorianCal );
}
}
My new version is :
private XMLGregorianCalendar asXMLGregorianCalendar(Date data) throws ComponentBlockingException {
if (data == null) {
return null;
}
DatatypeFactory dateformat = null;
try {
dateformat = DatatypeFactory.newInstance();
} catch (MyException e) {
////
}
GregorianCalendar gregorianCal = new GregorianCalendar();
gregorianCal.setTimeInMillis(data.getTime());
return dateformat.newXMLGregorianCalendar(gregorianCal );
}
}
I think the second way should be ok.
I am not sure about any available online code anlayzer tool but let me try to help you with your code analysis.
If due to some reason following try block hits an an exception
try {
dateformat = DatatypeFactory.newInstance();
}
then your dateformat will remain null. So the following statement
return dateformat.newXMLGregorianCalendar(gregorianCal );
is prone to null pointer exception. And hence i believe you are getting static code anlayzer error.
You have to make sure dateformat is initialized or non-null in all the case before code reaches the line where you are doing the return.
Hope it helps!
I am working on a Java web base project, where I am using web service to access date and update the date, my screen has a date field, which I need to update with the data acquired form the web service, but the web service date is of type XMLGregorianCalendar.
This is what I have:
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try {
date = (Date)df.parse("5-5-2012");
System.out.println("Date Date" + date);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);
System.out.println(""+gregory);
XMLGregorianCalendar calendar =null;
try {
calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregory);
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
calendar.setTimezone( DatatypeConstants.FIELD_UNDEFINED );
someDoa.setdate(calendar);
}
}
But the result is:
SEVERE: Servlet.service() for servlet default threw exception
javax.xml.ws.soap.SOAPFaultException: java.lang.IllegalArgumentException: Incorrect Offset :Incorrect Offset :needs a leading +/- sign