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

2 Answers

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.
0 votes
ago by (2.8k points)

DateFormat.format only works on Date values.
You can use two SimpleDateFormat objs.: one for parsing, and one for formatting. For example:

// MM is months, not mm
DateFormat format_in = new SimpleDateFormat("MM/yyyy", Locale.India);
DateFormat input_value=new  SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX",Locale.India);

String input_value = "2024-12-19T00:00:00.000-06:00";
Date date = format_in.parse(input_value);
String output_value = outputFormat.format(date);

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...