Hello. I'm trying to convert Calendar to dd/MM/yyyy format.

My problem was it couldn't convert to exactly what i wanted. I'm Turkish so when we write a date, we write the day first then month then year...


My code is here

public static String toFormattedDateString(Calendar input){
		String year = null;
		String month = null;
		String day = null;
		if(input.get(Calendar.MONTH)<9){
			System.out.println("Calendar.MONTH--->"+input.get(Calendar.MONTH));
			int monthInt = input.get(Calendar.MONTH);
			monthInt++;
			month = "0";
			month += (new Integer(monthInt)).toString();
		}
		else 
			month = (new Integer(input.get(Calendar.MONTH)+1)).toString();
		
		if(input.get(Calendar.DAY_OF_MONTH)<10)
			day = "0"+ (new Integer(input.get(Calendar.DAY_OF_MONTH))).toString();
		else
			day = (new Integer(input.get(Calendar.DAY_OF_MONTH))).toString();
		year = new Integer(input.get(Calendar.YEAR)).toString();
		
		return day+"/"+month+"/"+year;
	}

And it can't convert to what i want exactly. Here are some results.


01.02.2009---> It couldn't convert it correctly. Added dots and 01 is the month and 02 is the day.
17/01/2009 ---> This is the correct result. dd/MM/yyyy format
01.02.2009----> Wrong again.

Recommended Answers

All 6 Replies

Have a look at SimpleDateFormat, it allows you to format dates according to your locale and your own format specification.
It works with Date objects, rather than Calendars, so use the getTime() Calendar method to get the correponding Date.

public static String toFormattedDateString(Calendar input){
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd/MM/yyyy");
return df.format(input.getTime());
}

The same results again. I don't know what's wrong with this.

What is the exact input data that you are using? and what is the exact output?
Maybe the roblem is in how the Calendar object is beung set up before this method is called?

I have an HTML table and i get this table as a result.

My result is correct.

It's like this.

<table>
<tr>
<td>
03/02/2009
</td>
<td>
03/02/2009
</td>
</tr>
</table>

Then in the servlet i do this;

response.setHeader("Content-Disposition", "attachment; filename = Report.XLS");
response.setContentType("application/vnd.ms-excel");
response.getWriter().write(result);//--->this is my HTML table above
response.getWriter().flush();

The result in excel is this

02.03.2009 02.03.2009

The table data which are like 22/10/2009 or 13/01/2009 are correct in excel. I can see them in the correct format.

It writes correct in the console. But the problem is while converting the table to the excel file.

I would check the format that Calendar is using to read this data.

I used . instead of / and this fixed the problem...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.