Im trying to save two dates into a serialized . bin
file. I use the Calendar class
to get the current date then I add 30 days onto it. So I try to save two date variables fd
(First Date) and ed
(Expiration Date). If I change them to Strings
in the expiration_date_serial file they work, but when I try to save them as Date
they throw errors on these 2 lines:
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
Error: incompatible types: java.lang.String cannot be converted to java.util.Date
Runnable Class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class GetCurrentDate {
public static void main(String[] args) {
// get current date
DateFormat currentdateFormat = new SimpleDateFormat("MM/dd/yy");
Date current_date = new Date();
String current_formateddate = currentdateFormat.format(current_date);
System.out.println("Current date: " + (current_formateddate));
// ADD 30 days to the current date
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 30);
Date d = c.getTime();
String formateddate = dateFormat.format(d);
System.out.println("+ 30 days: " + formateddate);
// Serialization start
expiration_date_serial exp_date = new expiration_date_serial();
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
String fileName = "data.bin";
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(fileName));
os.writeObject(exp_date);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done writing...");
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
fileName));
expiration_date_serial p = (expiration_date_serial) is.readObject();
System.out.println("First Date = " + p.fd +
" Expiration Date = " + p.ed);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Other class:
import java.io.Serializable;
import java.util.Date;
public class expiration_date_serial implements Serializable {
public Date fd;//First Date
public Date ed;//Expiration Date
}