Java Puzzle : String concatenation

I have simple program to print date after month from now.

   1: package com.test;
   2:  
   3: import java.text.ParseException;
   4: import java.text.SimpleDateFormat;
   5: import java.util.Date;
   6:  
   7: public class Test{
   8:     public static void main(String[]args) throws ParseException{
   9:         Date currentDate = new Date();
  10:         int d = currentDate.getDate();
  11:         int month = currentDate.getMonth()+1;
  12:         int year = currentDate.getYear() +1900;
  13:         //trying to update to next moth same date
  14:         Date nextMonthDate = new SimpleDateFormat("dd-MM-yyyy")
  15:                 .parse(d + "-" 
  16:                   + month+1 + "-" // increasing month by one to get next month
  17:                   + year);
  18:         System.out.println("Current Date = "+ currentDate);
  19:         System.out.println("Next Month Date = "+nextMonthDate);
  20:     }
  21: }



output for this problem is



   1: Current Date = Fri Apr 22 03:59:56 IST 2011
   2: Next Month Date = Thu May 22 00:00:00 IST 2014

One thing needs to notices here , month is as expected increased by one but year increased by 3 years .


Did you find anything fishy ……….?

Comments

  1. Why are you adding 1900 to year?
    int year = currentDate.getYear() +1900;

    ReplyDelete
  2. currentDate.getYear() gets count of years after 1900, thats why i am adding 1900.
    Try same code runnung :)

    ReplyDelete
  3. Line 16 does string concatenation because there is a string prior to that addition.
    Instead of 3 + 1 it becomes 31.

    ReplyDelete
  4. I run the same code but get Different output like this..!!

    Current Date = Sun Sep 09 21:43:34 IST 2018
    Next Month Date = Wed Jul 09 00:00:00 IST 2025

    can anyone explain why there is different output in month and years too from current date ??

    ReplyDelete

Post a Comment

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example