Sanjana
Sanjana

Reputation: 467

Converting String to Date using SimpleDateFormat

I am taking a String input from user , which I want to convert into java.util.Date instance and print it into specific manner using SimpleDateFormat .It is not printing in the specified manner.

try {           Date date1;
            date1 = new SimpleDateFormat("MM/dd/yy").parse("05/18/05");
            System.out.println(date1);
        } 

        catch (ParseException e) {

            e.printStackTrace();
        }

Upvotes: 0

Views: 240

Answers (3)

Karthik Prasad
Karthik Prasad

Reputation: 10034

Try this

try {
            SimpleDateFormat sdin = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdout = new SimpleDateFormat("yyyy-MMM-dd");
            Date date = sdin.parse("2013-05-31");
            System.out.println(sdout.format(date));
        } catch (ParseException ex) {
            Logger.getLogger(TestDate.class.getName()).log(Level.SEVERE, null, ex);
        }

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

You need to format your date before you print it out, otherwise you use Date's default format

try {           
   Date date1;
   SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
   date1 = format.parse("05/18/05");
   System.out.println(format.format(date1));
} 

When you do

System.out.println(date1);

internally, the method is calling

date1.toString();

and prints its result. Date#toString() is implemented as follows

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == gcal.SUNDAY) {
        index = 8;
    }
    convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
}

which results in the Date string you are seeing.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533870

It is not printing in the specified manner.

System.out.println(date1); // no format given, using the default format

You are not specifying a manner. The date has a no history of the format it was parsed from. If you want a format, you need to use SimpleDateFormat.format()

Upvotes: 2

Related Questions