I have a simple class called DateTime because I'm doing some interface with a C# web service. I wanted to override the Date class' toString method as shown below in order to serialize it in a way C# understands, so I wrote a simple little wrapper class. The problem comes when trying to cast a Date type as DateTime. Is there any way to do something along the lines of:

(DateTime)Calendar.getInstance().getTime();

I tried the above cast and got a ClassCastException. Is there any way to do this or something similar? My class definition is below.

private class DateTime extends Date {
  @Override
  public String toString() {
    int year= getYear();
    int month= getMonth();
    int day= getDay();
    int hour= getHours();
    int minute= getMinutes();
    int second= getSeconds();
    return String.format("%04d-%02d-%02dT%02d:%02d:%02d", year, month, day, hour, minute, second);
  }
}

Recommended Answers

All 3 Replies

Member Avatar for coil

The reason you're getting errors is because Calendar has no relation to DateTime.

If you want to override the Date class' toString(), then why not just use the DateTime class that you've already created? Either that, or directly extend Calendar and use that.

Calendar.getInstance().getTime() returns an object of type Date. I still don't understand why the above explicit cast doesn't work.

Trying to directly extend Calendar, I get a series of required methods that I can't pass off to the super class because it's all abstracted. I tried using GregorianCalendar instead and still get the same casting problem.

Casting to a subclass of the objects actual type doesn't work. The subclass may contain variables and constructor code that the superclass does not have, so simply pretending its a subclass instance isn't going to work.
You can create a kind of copy constructor like this:

public DateTime(Date d) {
        super(d.getTime());
     }

And create an instance directly like this:

DateTime d = new DateTime(Calendar.getInstance().getTime());
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.