cancel
Showing results for 
Search instead for 
Did you mean: 

can't turn String to Date in the format i want

Former Member
0 Kudos

Hello everyone,

I have a problem I need to solve quickly,

basically I have a date which I set to a certain format using SimpleDateFormat but I need it as a Date in that format so I can add it to my database

I have some code but it doesn't work as I want it to.

After I parse the date pdate is still null and it doesn't print the line in the try-catch clause. Is there anyway to set a Date d to be in the format I want it and not just a String? (because if I print out the string it's exactly how I want it)

here's the code (I know it's not the neatest thing but I'm just trying things out), thanks all in advance I really appreciate the help


int prevy = (int) (Integer.parseInt(prevyear.getText()));
int prevm = (int) (Integer.parseInt(prevmonth.getText()));
int prevd = (int) (Integer.parseInt(prevday.getText()));
java.util.Date prevdate = new java.util.Date(prevy-1900,prevm-1,prevd);
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
String prevdte = format.format(prevdate);

java.util.Date pdate=null;
try {
	java.text.SimpleDateFormat df=new java.text.SimpleDateFormat("yyyy-mm-dd");
	pdate = df.parse(prevdate.toString());
	System.out.println("pdate: " + pdate);
}
catch (ParseException err) {
}

System.out.println("pdate: " + pdate);

Accepted Solutions (1)

Accepted Solutions (1)

Vlado
Advisor
Advisor
0 Kudos

Hi Alex,

> After I parse the date pdate is still null and it doesn't print the line in the try-catch clause.

This implies that a ParseException occurs in the <i>df.parse(prevdate.toString());</i> method but you have hidden it. Just add an <i>err.printStackTrace()</i> to the catch clause to see what's gone wrong.

BTW, the Date(int year, int month, int date) constructor is deprecated. Check the documentation of <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Date.html">java.util.Date</a> to see what would suit you best in this case.

Hope that helps!

-Vladimir

Answers (1)

Answers (1)

Former Member
0 Kudos

thanks, i kind of figured that's what was happening but i didn't understand why. I think i managed to get around it though by passing it into a java.sql.Date which is what i think i would need anyway but thanks a lot for your help

Alex