1

Problematic code:

public static final String DATEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

public static String getAsString(Object dateStr)
{

    if ( dateStr== null || dateStr.toString().equalsIgnoreCase("null"))
    {
        return null;
    }
    // here I am getting exception
    return (new SimpleDateFormat(DATEFORMAT)).format((Timestamp)dateStr);  
}

Can you please help me to avoid the class cast exception?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Deepika
  • 99
  • 1
  • 2
  • 8
  • 4
    Well presumably `dateStr` is a string, given the error message. Why are you accepting an `Object` reference if you actually require it to be a `Timestamp`? The way to avoid the exception is to not cast things inappropraitely... but we have no idea what's in the string, so we can't help you convert that into a `Timestamp`... – Jon Skeet Sep 28 '16 at 05:49
  • refer this link for answer http://stackoverflow.com/questions/25892417/caused-by-java-lang-classcastexception-java-sql-timestamp-cannot-be-cast-to-ja – thedudecodes Sep 28 '16 at 05:52
  • The value of dateStr is 2016-09-28T00:00:00Z – Deepika Sep 28 '16 at 10:48

2 Answers2

3

Instead of casting the String to a Timestamp, you can use the function Timestamp.valueOf(String).

cstr_
  • 98
  • 6
  • public static final String DATEFORMAT = "yyyy-MM-dd 'T'HH:mm:ss'Z'"; public static String getAsString(Object dateStr) { if ( dateStr== null || dateStr.toString().equalsIgnoreCase("null")) { return null; } // here I am getting exception return (new SimpleDateFormat(DATEFORMAT)).format(Timestamp.valueOf(dateStr)); } passing value as 2016-09-28 T00:00:00 Z – Deepika Sep 28 '16 at 10:46
0

You just can't do this because you have no idea what's in the string. Maybe the datestr in your code is like this "abcdredsad". If your are sure that this datestr object is a date string,and you just want to change the formatter from "yyyyMMdd HH:mm:ss" to "yyyy-MM-dd HH:mm:ss", try this.

public static void main(String[] args) {
    String date = StringToDate("20160928 15:00:00");
    System.out.println(date);
}

public static String StringToDate(Object datestr) {
    Date d = new Date();// note: set a default value here 
    Date date;      
    if (datestr == null)
        return null;    
    // you must know the old pattern of the datestr in your code
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    try {
        d = sdf.parse(datestr.toString());// if your formatter is wrong, exception occurs here.
    } catch (ParseException e) {
        e.printStackTrace();
    }
    date = new Date(d.getTime());// if d didn't have a default value, wrong here.

    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    return sdf.format(date);
}
  • I saw the suggestion below,and it remind me of this.It's an Exception: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] – stackoverflow Sep 28 '16 at 06:52