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:


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 {
  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);
8 Years
Discussion Span
Last Post by JamesCherrill

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.

Edited by c++noobie: n/a


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) {

And create an instance directly like this:

DateTime d = new DateTime(Calendar.getInstance().getTime());
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.