Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

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

This is my code

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

    }    

}

And when I run the code it is throwing 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)

1 Answer

0 votes
by (13.1k points)

DateFormat.format only works on Date values.

You should use two SimpleDateFormat objects: one is for parsing and the other for formatting.

For example:

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

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

Browse Categories

...