47370

Parsing String date to date [duplicate]

Question:

This question already has an answer here:

<ul><li> <a href="/questions/14755742/java-date-year-calculation-is-off-by-year-for-two-days" dir="ltr" rel="nofollow">Java Date year calculation is off by year for two days</a> <span class="question-originals-answer-count"> 5 answers </span> </li> </ul>

I have a date String in this format "YYYY-MM-dd HH::mm:ss". Every time i parse the string i get wrong date.("Sun Dec 29 10:10:10 CET 2013"). The code is below:

DateFormat timeFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); Date startDate = timeFormat.parse("2014-08-10 10:10:10"); System.out.println(startDate);

This returns "Sun Dec 29 10:10:10 CET 2013". How to correctly parse the date String?

Answer1:

Rather than using YYYY you will need to use yyyy.

Y Refers to WEEK_YEAR whereas y refers to YEAR. WEEK_YEARs are based on when the first full week of a year starts (this differs depending on settings), and thus are slightly (and sometimes largely) different from that of YEAR.

See the javadoc: <a href="http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#week_year" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#week_year</a>

Answer2:

You are using wrong format. You need yyyy instead of YYYY.

If you take a look at <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="nofollow">SimpleDateFormat documentation</a> you will find that

y Year Y Week year

where "<a href="http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#week_year" rel="nofollow">week year</a>" is in sync with a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#WEEK_OF_YEAR" rel="nofollow">WEEK_OF_YEAR</a> cycle.

Now, why YYYY returns 2013 for year 2014?

To answer this question you need to understand how calendar determines that week belongs to some year. Rule is quite simple:

<ul><li>week belongs to year XXXX if last N days of this week (usually N=4 but it is determined by getMinimalDaysInFirstWeek from used Calendar) belongs to year XXXX</li> <li>weeks starts at day which is result from getFirstDayOfWeek. This result depends on Locale but in next examples we will use Monday as first day of week.</li> </ul>

<strong>Example 1.</strong>

Assuming that first day of week is Monday and days required for week to belong to some year is 4 lets try to determine which week is first in year XXXX for January which looks like this:

January XXXX Mon Tue Wed Thu Fri Sat Sun 27 28 29 30 31 1 2 3 4 5 6 7 8 9 ...

Week from first row contains only two days which belongs to year XXXX (to January), 1st and 2nd

27 28 29 30 31 1 2 ^^^ ^^^ //days which belong to January

but this is less than number of days required for this week to belong to XXXX year while next week

3 4 5 6 7 8 9

contains 7 days which belong to XXXX year. Since week in first row doesn't belong to year XXXX <em>first week</em> in <em>week year</em> will start 3 January XXXX. This means that if we parse value XXXX with format YYYY we will get 3rd January XXXX.

<strong>Example 2.</strong>

Now lets say that calendar for year XXXX looks like this

January XXXX Mon Tue Wed Thu Fri Sat Sun 30 31 1 2 3 4 5 6 7 8 9 10 11 12 ...

As you can see in week

30 31 1 2 3 4 5

its last 5 days belong to year XXXX which is more than required 4 days<br /> -> which means that this week belongs to year XXXX,<br /> -> and it is also first week of XXXX year<br /> -> which means that first week of this year starts at 30 December (XXXX-1)<br /> -> which finally means that if you parse such year using YYYY format you will get value XXXX-1.

<hr />

<strong>Example 2</strong> is actually situation from year 2014, which is why year was interpreted as year 2013.

BTW, if you would decide to use format with week year to set month and day you would also need to use special formats which would describe

<ul><li>which week of year you want to set </li> <li>and which day of week </li> </ul>

so instead of M and d you would have to use

w Week in year u Day number of week (1 = Monday, ..., 7 = Sunday)

(hours, minutes, seconds are part of time rather than date so H m and s are fine in this format)

for instance

DateFormat format = new SimpleDateFormat("YYYY-ww-uu HH:mm:ss"); Date date = format.parse("2004-53-7 10:10:10"); System.out.println(date);

which will be parsed to Sun Jan 02 10:10:10 CET 2005

Recommend

  • Why some controls has both BackgroundImage and Image property?
  • Optimize performance for queries on recent rows of a large table
  • Core Data vs SQLite [closed]
  • Using an R Markdown Document as a source for functions
  • Status bar overlaps toolbar
  • Difference between a changeset and a patch?
  • Memory usage differs greatly (and strangely) between frontend and backend
  • function cannot execute on segment because it accesses relation
  • AngularJs ng-repeat filtering by a deeper tier of data
  • Is there a way to read an Excel file using Dataflow
  • Send http request through specific network interface
  • Java Date object constructor for getting string is deprecated
  • Is it possible to disable certain weekdays in DatePickerDialog?
  • Get or convert Week of year to ISO week
  • Stacked Bar Chart with percentage composition inside the Bar and total above the Bar in JFreeChart
  • Angular2 & SystemJS : Cannot find module while building a moduleLoader
  • Use allowDiskUse in criteria query with Grails and the MongoDB plugin?
  • JsonConverter: Get parent object in ReadJson, without $refs
  • Obtain actual browser URL in PHP
  • How does inheritance and polymorphism work in this situation?
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Classic ASP URL Rewriting
  • Efficient User-Agent Regex to find Safari in Python
  • What does “t” refer to in this SQL?
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • jQuery ready not fired after rails link_to is clicked
  • Visual Studio 2010 debugger build correctly - compiler pdb and linker pdb not in synch?
  • How to get Eclipse Oxygen to run on Java 9
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Refering to the class itself from within a class mehod in Objective C
  • Yii2: Config params vs. const/define
  • Python CGI os.system causing malformed header
  • Algorithm for a smudge tool?
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Java applet as stand-alone Windows application?
  • Javascript convert timezone issue
  • Jquery - Jquery Wysiwyg return html as a string
  • XCode can't find symbols for a specific iOS library/framework project
  • Confusion with PayPal's monthly billing cycle
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value