Vikash Kumar
Vikash Kumar

Reputation: 395

Date Format Gives Wrong Result

I'm trying a code in java to convert a String into Date but I'm getting the output wrong. Can you please help me out to sort out it.

Here is my java code

import java.text.*;
import java.util.*;

public class My {

public static void main( String[] args ) {

    String textDate = "31/12/2015";
    Date actualDate = null;

    SimpleDateFormat yy = new SimpleDateFormat( "MM/dd/yy" );
    SimpleDateFormat yyyy = new SimpleDateFormat( "MM/dd/yyyy" );

    try {
        actualDate = yy.parse( textDate );
    }
    catch ( ParseException pe ) {
        System.out.println( pe.toString() );
    }

    System.out.print( textDate + " enhanced:  " );
    System.out.println( yyyy.format( actualDate ) );
}
}

Output I got:

31/12/2015 enhanced: 07/12/2017

Upvotes: 0

Views: 469

Answers (3)

NewBee Developer
NewBee Developer

Reputation: 432

Change SimpleDateFormat yy = new SimpleDateFormat( "MM/dd/yy" ); to SimpleDateFormat yy = new SimpleDateFormat("dd/MM/yy");

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201409

The date you are trying to parse is not in Month/Day/2 digit year format.You need something like

SimpleDateFormat yy = new SimpleDateFormat( "dd/MM/yyyy" );

or change the String like

String textDate = "12/31/15";

Upvotes: 2

LordAnomander
LordAnomander

Reputation: 1123

The sequence of your code is wrong. You cannot parse dd/MM/yyyy to dd/MM/yy, so you have to use yyyy.parse(textDate) at first and use yy.format(actualDate) later to get 31/12/15.

Upvotes: 0

Related Questions