[java] Java : Cannot format given Object as a Date

I have Date in this format (2012-11-17T00:00:00.000-05:00). I need to convert the date into this format mm/yyyy.

I tried this way, but I am getting this Exception.

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at DateParser.main(DateParser.java:14)

Please see my code below:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParser {    
    public static void main(String args[]) {   
        String MonthYear = null;    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm/yyyy");    
        String dateformat = "2012-11-17T00:00:00.000-05:00
        MonthYear = simpleDateFormat.format(dateformat);    
        System.out.println(MonthYear);    
    }    
}

This question is related to java

The answer is


DateFormat.format only works on Date values.

You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:

// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.


public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.


SimpleDateFormat.format(...) takes a Date as parameter and format Date to String. So you need have a look API carefully


java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links


You have one DateFormat, but you need two: one for the input, and another for the output.

You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.

DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

I have resolved it , this way

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateParser {

    public static void main(String args[]) throws Exception {

        DateParser dateParser = new DateParser();

        String str = dateParser.getparsedDate("2012-11-17T00:00:00.000-05:00");
        System.out.println(str);
    }


    private String getparsedDate(String date) throws Exception {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        String s1 = date;
        String s2 = null;
        Date d;
        try {
            d = sdf.parse(s1);
            s2 = (new SimpleDateFormat("MM/yyyy")).format(d);

        } catch (ParseException e) {

            e.printStackTrace();
        }

        return s2;

    }

}