1.简单获取年月日
代码示例:
package others; import java.util.Calendar; public class CalenderDemo1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Calendar c = Calendar.getInstance(); //得到年 sop(c.get(Calendar.YEAR)+"年"); sop(c.get(Calendar.MONTH)+1+"月"); sop(c.get(Calendar.DATE)+"号"); } public static void sop(Object obj){ System.out.println(obj); } }
2.由于获取月总是加1,可以用数组下标来实现(查表法获取月,星期):
代码示例:
package others; import java.util.Calendar; public class CalenderDemo1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Calendar c = Calendar.getInstance(); //查表法获得月 String [] months = {"一月","二月","三月","四月", "五月","六月","七月","八月", "九月","十月","十一月","十二月"}; String[] weeks = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; int index = c.get(Calendar.MONTH); int index2 = c.get(Calendar.DAY_OF_WEEK); sop(c.get(Calendar.YEAR)+"年"); sop(months[index]); sop(c.get(Calendar.DATE)+"号"); sop(weeks[index2]); } public static void sop(Object obj){ System.out.println(obj); } }
3.自定义的时间:
代码示例:
package others; import java.util.Calendar; public class CalendarDemo2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Calendar c = Calendar.getInstance(); //此时设置月份的时候注意下标和月份的比配,比如:0代表的是1月 c.set(2018, 3, 8); //在此设置的月份上减1个月 c.add(Calendar.MONTH, -1); printCalendar(c); } public static void printCalendar(Calendar c) { String[] months = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" }; String[] weeks = { "", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; int index = c.get(Calendar.MONTH); int index2 = c.get(Calendar.DAY_OF_WEEK); sop(c.get(Calendar.YEAR) + "年"); sop(months[index]); sop(c.get(Calendar.DATE) + "号"); sop(weeks[index2]); } public static void sop(Object obj){ System.out.println(obj); } }