Date as double digit
I've a code to get year, month and day for one of my application.
package com.cera.hyperionUtils;
import java.u开发者_开发技巧til.*;
public class HypDate {
public static int curdate(int field)
{
//1. Specify integer 1 for YEAR, 2 for MONTH, 5 DAY_OF_MONTH
Calendar c = new GregorianCalendar();
c.setLenient(true); //Allow overflow
//2. Extract and Return result
if (field == 2) {
field = c.get(Calendar.MONTH) + 1;
}
return c.get(field);
}
public static void main(String[] args)
{
System.out.println(HypDate.curdate(2));
}
}
But when i pass 2 it is giving 0 year and day prints correctly.....Also i was trying to make month as double digit. (like 01 for 1)
Can someone please help me....? (I''m very new to java coding)
Rather than returning these one by one, you may just want to use a SimpleDateFormat
to format it.
Say I want a date as year-month-day:
// Necessary imports
import java.text.DateFormat;
import java.text.SimpleDateFormat;
// Declare class and stuff before this
public static String getFormattedDate() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(new Date());
}
public static void main(String[] args) {
System.out.println(getFormattedDate());
}
Outputs 2010-10-29
Edit:
Since you just want the month, you can do this:
public static String getFormattedMonth() {
DateFormat df = new SimpleDateFormat("MM");
return df.format(new Date());
}
if (field == 2) {
field = c.get(Calendar.MONTH) + 1;
}
return c.get(field);
You retrieve the correct month as an index and then use that index to retrieve another field that will be unknown and related in how the constants are saved. Just return the value before, without using a second get
.
Maybe you meant
if (field == 2) {
field = Calendar.MONTH;
}
return c.get(field) + 1;
but I don't get why you are redefining that constants instead that use the one already provided..
The problem comes from the fact that when you are getting the month information, you call c.get() twice, which you don't want to do. Instead, you should directly return after you get the first value
//1. Specify integer 1 for YEAR, 2 for MONTH, 5 DAY_OF_MONTH
Calendar c = new GregorianCalendar();
c.setLenient(true); //Allow overflow
//2. Extract and Return result
if (field == Calendar.MONTH) {
return c.get(field) + 1; //because Java months are 0-based
} else {
return c.get(field);
}
精彩评论