javadatedatetimejodatime

Convert dateTime to date in dd/MM/yy format in java


I have a Joda-Time DateTime 2012-12-31T13:32:56.483+13:00. I would like to convert it to Date in dd/MM/yy format. So I'm expecting code to return Date like - 31/12/12.

Code -

    // Input dateTime = 2012-12-31T13:32:56.483+13:00
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
    Date date = simpleDateFormat.parse(dateTime.toString("dd/MM/yy"));

Results:

Output - Mon Dec 31 00:00:00 NZDT 2012
Expected Output - 31/12/12

When I do the following, I get the expected output but I don't know how to convert it to Date-

String string = simpleDateFormat.format(date); 

Please help me.

Thx

EDIT - I want my end result to be Util Date in dd/MM/yy format. I Do not want String output. My input is Joda DateTime yyyy-MM-ddThh:mm:ss:+GMT. I need to convert JodaDateTime to UtilDate.


Solution

  • As I said originally, Date objects do not have an inherent format. java.util.Date holds a millisecond time value, representing both date & time. Dates are parsed from string, or formatted to string, via your choice of DateFormat.

    The strings may be formatted per specification, but the Date objects behind them are always full precision & do not have any inherent notion of format.


    To truncate a combined "date and time" java.util.Date to just the date component, leaving it effectively at midnight:

    public static Date truncateTime (Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime( date);
        cal.set( Calendar.HOUR_OF_DAY, 0);
        cal.set( Calendar.MINUTE, 0);
        cal.set( Calendar.SECOND, 0);
        cal.set( Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
    

    If you're coming from JodaTime DateTime, you can do this more easily working mostly in the JodaTime API.

    public static Date truncateJodaDT (DateTime dt) {
        java.util.Date result = dt.toDateMidnight().toDate();
        return result;
    }
    

    Hope this helps!

    See:


    Now I'm unsure again, what you want. You want the date in string format now?

    return simpleDateFormat.format( date);    // from java.util.Date
    

    Or with JodaTime:

    return dateTime.toString( "dd/MM/yy");    // from org.joda.time.DateTime