• Post Reply Bookmark Topic Watch Topic
  • New Topic

Gregarion Calendar causing problem when adding dates.....  RSS feed

 
Deepak Shastri
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
output of incrementing below date 20050530 (30th April)by 1 is 31st April
instead of 1st May 2005 ?? Any explaination ?

import java.text.ParseException;
import java.util.*;
import java.io.*;
public class TestPgm {
public TestPgm() {
}

public static void main(String[] arg) throws ParseException
{
TestPgm t = new TestPgm();
t.extractDate("20050430");
}

public String extractDate(String xml_file_date)//20040728S
{
//String tempDate = latestFileName.substring(9,17).trim();
int yrIndex = Integer.parseInt(xml_file_date.substring(0,4));
int mthIndex = Integer.parseInt(xml_file_date.substring(4,6)) ;
int dayIndex = Integer.parseInt(xml_file_date.substring(6,8));

GregorianCalendar g = new GregorianCalendar(yrIndex,mthIndex,dayIndex);
System.out.println("mthIndex " + mthIndex);
System.out.println("dayIndex " + dayIndex);
System.out.println("yrIndex " + yrIndex);

g.add(Calendar.DATE,1);
String yr = g.get(GregorianCalendar.YEAR)+"";
String mth = g.get(GregorianCalendar.MONTH)+"";
if(mth.length() != 2)
{
mth = "0"+mth;
}
String day = g.get(GregorianCalendar.DATE)+"";
System.out.println("yr " + yr);
System.out.println("mth " + mth);
System.out.println("day " + day);

if(day.length() != 2)
{

day = "0"+day;
}

return yr+""+mth+""+day;
}


}
 
Horatio Westock
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is that it's something to do with the fact that unlike days, months are zero indexed.

The 'safe' way to do this is not to parse the date yourself. Use SimpleDateFormat.parse().

E.g.

 
Nischal Tanna
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have not read ur question but for ur info month in GregorianCalendar starts from 0 i.e., (0 to 11)... so if u have month as 1 (it will be Feb, not Jan).. Hope this helps in some way
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!