javadatetimestampsimpledateformatdeprecated

java.text.ParseException: Unparseable date Exception while converting timestamp value to time in java


I want to convert a Timestamp value which is passed as String to SimpleDateFormat Object into Time Value but it throws a Unparseable date exception.

The Value which i am passing is Thu Jan 1 17:45:00 UTC+0530 1970

Bur i am getting an Exception as mentioned below:

java.text.ParseException: Unparseable date: "Thu Jan 1 17:45:00 UTC+0530 1970"

Please find the below code which i have implemented(Not Working):

static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
static SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
static SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");

public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
    {
        Date parsedDate = dateFormat.parse(utcDateValue);
        String returnDate=outputFormatTime.format(inputFormat.parse(parsedDate.toString()));
        return returnDate;
    }

If i use the below code it works fine for me(Working) but its a depreciated function of Date which i want to avoid..

@SuppressWarnings("deprecation")
public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
{
    Date dateValue=new Date(utcDateValue);
    Date parsedDate = dateFormat.parse(dateValue.toString());
    String returnDate=outputFormatTime.format(inputFormat.parse(parsedDate.toString()));
    return returnDate;
}

Please Guide Me To implement the logic where i have missed. Thanks in advance.


Solution

  • First of all, your 2nd SimpleDateFormat object, is not needed at all. You are doing the extra work, which is not needed. So, remove this variable:

    static SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);  // Not needed.
    

    Secondly DateFormat#format(Date) methods takes a Date object. You are passing it a String. That wouldn't work. That is why you don't need the above object. There is no need to do a inputFormat.parse(parsedDate.toString()) again.


    Now, the format to parse your current string should be:

    "EEE MMM dd HH:mm:ss 'UTC'z yyyy"
    

    You need to give the UTC in quotes, before z. Or for more general case:

    "EEE MMM dd HH:mm:ss zZ yyyy"
    

    So, your code should be like:

    static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zZ yyyy", Locale.US);
    static SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");
    
    public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
        {
            Date parsedDate = dateFormat.parse(utcDateValue);
            String returnDate=outputFormatTime.format(inputFormat);
            return returnDate;
        }