-1

I am using SimpleDateFormat class to set pattern and using the parse method to parse the String to Date object.

But when I am printing the Date object without using method format():

SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Date dat1 = format.parse("2017-11-01");
System.out.println(dat1);

My result is:

Sun Dec 30 00:00:00 UTC 1990

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
sri ram
  • 9
  • 2
  • 6
  • 1
    I can't reproduce that - I get January 2nd 2017. But fundamentally you want `yyyy` instead of `YYYY`. When you have problems with `SimpleDateFormat`, the **first** thing to do is check your format string really, really carefully against the documentation. (Note that the problem isn't how the resulting `Date` is being formatted - it's the parsing.) – Jon Skeet Nov 24 '17 at 17:20
  • 3
    The good solution is to drop the long outdated and notoriously troublesome `SimpleDateFormat` class and use `java.time`: `LocalDate.parse("2017-11-01")` will give you what you expect. The short-sighted solution is to use lowercase `yyyy` instead of uppercase in your format pattern string. – Ole V.V. Nov 24 '17 at 17:21
  • 1
    Thanks i got the my mistake resolved. I will try to user java.time. – sri ram Nov 24 '17 at 17:24

1 Answers1

0

tl;dr

LocalDate.parse( "2017-11-01" ) 

Results not reproducible

Your results cannot be reproduced. See code run live at IdeOne.com:

SimpleDateFormat format = new SimpleDateFormat( "YYYY-MM-dd" );
Date dat1 = format.parse( "2017-11-01" );
System.out.println( dat1 );

Sun Jan 01 00:00:00 GMT 2017

java.time

You are using troublesome old legacy classes now supplanted by the java.time.

LocalDate ld = LocalDate.parse( "2017-11-01" ) 

ld.toString(): 2017-11-01


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154