Java Date issue
I am using GregorianCalander and when i tried to get todays date using the following code i am getting a date which is backdated to one month. The code i have used is as follows.
Calendar gcal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = getTime(gcal);
//date = dateFormat.format(calendar.getTime());
System.out.println("Today: " + today);
Please help me to solve this issue.
The output is :
Today: Thu Apr 28 00:00:00 NZST 2011
EDIT
private Date getTime(Calendar gcal) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String day = form_helper.round(gcal.get(GregorianCalendar.DAY_OF_MONTH));
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH));
String year = form_helper.round(gcal.get(GregorianCalendar.YEAR));
String date = day + "/" + month + "/" + year;
System.out.println(sdf.parse(date));
return sdf.parse(date);
} catch (ParseEx开发者_StackOverflowception ex) {
Logger.getLogger(timesheet_utility.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I think internal numbering of months starts with 0, not 1. So, you probably need to somewhere add +1.
Edit: after you showed some more code: The needed change is
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH) + 1);
What does the getTime()
method do? Remember that in Java, the constants for the month begin at 0 and not at 1, so Calendar.JANUARY == 0
.
EDIT
Since you posted the code for getTime()
I think this is the problem:
gcal.get(GregorianCalendar.MONTH)
returns the month value that Java internally stores, that is, a 0-indexed month value so a value for "May" would actually be the integer "4".
When the value "4" is put back into the date parser, "April" results, since the parser interprets dates as a human would. So you simply have to add 1 to this value to ensure the parsing happens properly.
If you want a Date
object that represents 12:00AM (or 00:00) for today, why not just do:
private Date getTime() {
Calendar gcal = new GregorianCalendar();
gcal.set(Calendar.HOUR_OF_DAY, 0);
gcal.set(Calendar.MINUTE, 0);
gcal.set(Calendar.SECOND, 0);
gcal.set(Calender.MILLISECOND, 0);
return gcal.getTime();
}
Here's my attempt:
package forums;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Deepak
{
public static void main(String[] args) {
try {
(new Deepak()).run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
Calendar calendar = new GregorianCalendar();
Date today = calendar.getTime();
System.out.println("Today: " + today);
}
}
and the output is the expected:
Today: Sat May 28 22:00:52 EST 2011
精彩评论