Freakyuser
Freakyuser

Reputation: 2814

Converting calendar to date in dd-MMM-yyyy format

I am trying to add 17 days to 10-APR-2014 and convert the date to dd-MMM-yyyy format, but I am getting Sun Apr 27 00:00:00 GMT+05:30 2014.

Here is my code:

import java.util.*;
import java.text.*;
public class HelloWorld{

    public static void main(String []args){
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 17);
        String output = sdf.format(c.getTime());
        System.out.println(output);
        System.out.print(new SimpleDateFormat("dd-MMM-yyyy").parse(output));
    }
}

How can I make the output be 27-Apr-2014?

Upvotes: 1

Views: 4659

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 340098

The answer by Bohemian is correct. Here I present an alternative solution.

Avoid j.u.Date

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.

Date-Only

If you need only a date, without any time component, both Joda-Time and java.time offer a LocalDate class.

Time Zone

Even for a date-only, you still need a time zone to get "today". At any moment the date may vary ±1 depending on your location on the globe. If you do not specify a time zone, the JVM's default time zone will be applied.

Example Code

Here is some example code in Joda-Time 2.3.

Determine "today" based on some time zone. Add seventeen days.

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
LocalDate today = new LocalDate( timeZone );
LocalDate seventeenDaysLater = today.plusDays( 17 );

Generate a String representation of the date-time value…

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MMM-yyyy" );
String output = formatter.print( seventeenDaysLater );

Dump to console…

System.out.println( "today: " + today );
System.out.println( "seventeenDaysLater: " + seventeenDaysLater );
System.out.println( "output: " + output );

When run…

today: 2014-04-21
seventeenDaysLater: 2014-05-08
output: 08-May-2014

Upvotes: 0

Bohemian
Bohemian

Reputation: 425328

You are printing a Date parsed from a String formatted from the calendar date.

Instead, print the formatted calendar date:

System.out.print(new SimpleDateFormat("dd-MMM-yyyy").format(c.getTime()));

If displaying and using the dates is disjunct, do this:

Date date; // from Calendar or wherever
String str = new SimpleDateFormat("dd-MMM-yyyy").format(date));
// display str 

Then when you want to do something with a selected date:

String selection;
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse(selection));
// do something with date

Upvotes: 3

Related Questions