-1

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
}
Community
  • 1
  • 1
javajoejuan
  • 323
  • 3
  • 9

2 Answers2

3

In Java, you cannot assign a value of type String to a field of type Date, that's why the error. It happens even before the serialization.

Your most obvious options are:

  • change a type of the field to String
  • don't convert Date objects to String and save them as is

You should decide what suits your needs better.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
0

tl;dr

LocalDate.now( ZoneId.of( "America/Montreal" ) )
         .plusDays( 30 )
         .toString()

Details

The Answer by Orlangure is correct, about assigning across types.

Also, other problems include:

  • Using old outmoded legacy classes for date-time handling.
  • Poor choice of format for serialized date values.
  • Incorrectly choosing to use a date-time class for a date-only value.

java.time

The old date-time classes are poorly-designed, confusing, and troublesome. Avoid them. Now legacy, supplanted by the java.time classes.

ISO 8601

The ISO 8601 standard defines textual formats for date-time values. These formats are unambiguous, intuitive across cultures, and practical. The standard format for a date-only value is YYYY-MM-DD such as 2016-10-23.

The java.time classes use ISO 8601 by default when parsing and generating Strings to represent their date-time values.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Strings

To generate an ISO 8601 compliant String, simply call toString.

String output = today.toString();  // 2016-10-23

To parse, simply call parse.

LocalDate ld = LocalDate.parse( "2016-10-23" );

Date math

You can add or subtract amounts of time. Just call the plus… and minus… methods.

LocalDate thirtyDaysAgo = ld.minusDays( 30 );
LocalDate oneMonthAgo = ld.minusMonths( 1 );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154