-5

I'm trying to create a Date or Calendar object from a String representation of the date in Java. I tried using SimpleDateFormat.parse, but the result produced is totally different from what I gave as input. Can someone explain what I'm doing wrong here?

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class IdeOne
{
  public static void main (String[] args) throws java.lang.Exception
  {
    SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date dt = sdf.parse("20141208");
    System.out.println(dt.getDay() + " " + dt.getMonth() + " " + dt.getYear());
    System.out.println(sdf.format(dt));
  }
}

I am getting output

0 11 113
20141229
Adi
  • 2,364
  • 1
  • 17
  • 23
  • 1
    you can post your code within the question. Don't link to other site for just showing your code. In case of complex problem, it might be useful. – mtk Dec 16 '14 at 08:00

2 Answers2

1

You have to use lower y for year :

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

Because upper Y is week year. For more information read the documentation of SimpleDateFormat

Jens
  • 67,715
  • 15
  • 98
  • 113
0

Try to use This:

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date dt = sdf.parse("20141208");
                Calendar c=Calendar.getInstance();
                c.setTime(dt);
                System.out.println(c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.MONTH)+ " " + c.get(Calendar.YEAR));
        System.out.println(sdf.format(dt));
    }
}
Manoj Sharma
  • 596
  • 1
  • 6
  • 23