Java中由Calendar类获取的月、天和小时的简单处理
在Java中,Calendar是日期处理的一个重要的类。但是,我们使用Calendar获取的月份,天,小时等可能需要进行简单的处理才能满足我们的需要。比如,月份范围是0-11,而我们可能需要的是1-12;返回值是1位整数,我们可能需要转换成2位整数等。下面是一个非常简单的小例子:
package com.qs.number; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.junit.Test; public class Utils { public static Map<String, String> dealMonthDayHour(int month, int day, int hour) { Map<String, String> month_day_hour = new HashMap<String, String>(); month = month % 12 + 1;// get the real month month_day_hour.put("month", dealZeroToNine(month)); month_day_hour.put("day", dealZeroToNine(day)); month_day_hour.put("hour", dealZeroToNine(hour)); return month_day_hour; } public static String dealZeroToNine(int num) { if (num >= 1 && num <= 9) { return "0" + num; } return "" + num; } @Test public void showYearMonthDayHour() { Calendar calendar = Calendar.getInstance(); String year = String.valueOf(calendar.get(Calendar.YEAR)); Map<String, String> month_day_hour = Utils.dealMonthDayHour(calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY)); String month = month_day_hour.get("month"); String day = month_day_hour.get("day"); String hour = month_day_hour.get("hour"); System.out.println(year + "\t" + month + "\t" + day + "\t " + hour); } }
输出如下:
2017 01 03 12