Zouhair
Zouhair

Reputation: 651

get the right Month format date java

can any help, how to get the right date from an String like this "2014-01-10T09:41:16.000+0000" my code is:

    String strDate = "2014-01-10T09:41:16.000+0000";
    String day = "";
    String format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    Locale locale = new Locale("es", "ES");
    SimpleDateFormat formater = new SimpleDateFormat(format, locale);
    formater.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

    Calendar cal = Calendar.getInstance();

    try {
        cal.setTimeInMillis(formater.parse(strDate).getTime());
        String offerDate = cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
        System.out.println(offerDate);
    } catch (Exception e){
        System.out.println(e.getMessage());
    }

in the result i give something like this: "10-0-2014", i want the result like that "10-01-2014"

thanks in advance :)

Upvotes: 1

Views: 151

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338181

tl;dr

java.time.Instant                    // Represent a moment as seen in UTC.
.parse( 
    "2014-01-10T09:41:16.000+0000"
    .replace( "+0000" , "Z" )        // Strict compliance with ISO 8601. 
) 

java.time

You are using terribly-flawed legacy classes that have been supplanted by the modern java.time classes defined in JSR 310.

Instant

The Instant class represents a moment, a point on the timeline, as seen from an offset from UTC of zero hours-minutes-seconds.

ISO 8601

Your string nearly complies with the strict version of ISO 8601 standard. The standard tolerates an offset missing its COLON character, +0000 rather than +00:00. But the Instant class does not by default. So replace that part of the string. You can use Z as an abbreviation of +00:00, pronounced “Zulu”.

String input = "2014-01-10T09:41:16.000+0000".replace( "+0000" , "Z" ) ;
Instant instant = Instant.parse( input ) ;

See this code run at Ideone.com.

2014-01-10T09:41:16.000Z

2014-01-10T09:41:16Z

Upvotes: 0

Mureinik
Mureinik

Reputation: 310993

I think the easiest would be to use another formatter object to do the formatting instead of building it yourself:

try {
    Date d = new Date(cal.setTimeInMillis(formater.parse(strDate).getTime()));
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    String offerDate = format.format(d);
    System.out.println(offerDate);
} catch (Exception e){
    System.out.println(e.getMessage());
}

Upvotes: 1

Mark
Mark

Reputation: 590

The documentation states:

java.util.Calendar.MONTH

MONTH public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

-> Counting starts at 0 for Calendar.MONTH

Upvotes: 3

Related Questions