从日历获取日期

时间:2015-01-18 18:27:22

标签: java calendar

大家好,我的节目中收到的日期如下: 2015年1月18日

这是一个日历对象,我需要从对象获取日,月和年。现在我做的事情如下:

int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calender.MONTH + 1);
int year = date.get(Calender.Year);

输出结果为:

day = 18
month = 1
year = 2015

我的问题是,我希望在这种情况下获得月份,如01而不是1,因为稍后我的代码会解析该值,并且需要使用该格式。在那之前附加0是难看的,所以任何人都知道一个更好的方法吗?感谢

2 个答案:

答案 0 :(得分:3)

如果您需要将数据传递为" 01" int是错误的数据类型。您需要将其作为String传递。您可以使用SimpleDateFormat格式化日期。这样,您可以选择从日期和应该具有的格式中选择哪些元素。例如:

final Calendar calendar = Calendar.getInstance();
final Date date = calendar.getTime();
String day = new SimpleDateFormat("dd").format(date);    // always 2 digits
String month = new SimpleDateFormat("MM").format(date);  // always 2 digits
String year = new SimpleDateFormat("yyyy").format(date); // 4 digit year

您还可以格式化完整日期,如下所示:

String full = new SimpleDateFormat("yyyy-MM-dd").format(date); // e.g. 2015-01-18

JavaDoc for SimpleDateFormat完全解释了各种格式选项。请注意SimpleDateFormat不是线程安全的。

答案 1 :(得分:2)

你需要

int month = cal.get(Calender.MONTH) + 1; // 0..11 -> 1..12

获取月份的int(+必须在参数之外)。

如果你需要一个从该整数开始的前导零的字符串,你可以使用textformat:

System.out.printf("month=%02d%n", month);
String monthStr = String.format("%02d", month);

但是,您实际上不必通过整数来获取路线,您可以直接将Date的部分格式化为字符串:

monthStr = new SimpleDateFormat("MM", Locale.ENGLISH).format(cal.getTime());
相关问题