Java代码 1.Calendar calendar = new GregorianCalendar(2007, 11, 25,0,0,0); 2.Date date = calendar.getTime(); 3.System.out.println("2007 Christmas is:"+format.format(date)); Calendar calendar = new GregorianCalendar(2007, 11, 25,0,0,0); Date date = calendar.getTime(); System.out.println("2007 Christmas is:"+format.format(date));
java月份是从0-11,月份设置时要减1.
GregorianCalendar构造方法参数依次为:年,月-1,日,时,分,秒.
取日期的部分:
Java代码 1.int year =calendar.get(Calendar.YEAR); 2. 3.int month=calendar.get(Calendar.MONTH)+1; 4. 5.int day =calendar.get(Calendar.DAY_OF_MONTH); 6. 7.int hour =calendar.get(Calendar.HOUR_OF_DAY); 8. 9.int minute =calendar.get(Calendar.MINUTE); 10. 11.int seconds =calendar.get(Calendar.SECOND); int year =calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH)+1;
int day =calendar.get(Calendar.DAY_OF_MONTH);
int hour =calendar.get(Calendar.HOUR_OF_DAY);
int minute =calendar.get(Calendar.MINUTE);
int seconds =calendar.get(Calendar.SECOND);
取月份要加1.
判断当前月份的最大天数:
Java代码 1.Calendar cal = Calendar.getInstance(); 2.int day=cal.getActualMaximum(Calendar.DAY_OF_MONTH); 3.System.out.println(day); Calendar cal = Calendar.getInstance(); int day=cal.getActualMaximum(Calendar.DAY_OF_MONTH); System.out.println(day);
2.java.util.Date
Java代码 1.java.util.Date today=new java.util.Date(); 2.System.out.println("Today is "+formats.format(today)); java.util.Date today=new java.util.Date(); System.out.println("Today is "+formats.format(today));
取当月的第一天:
Java代码 1.java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-01"); 2.java.util.Date firstDay=new java.util.Date(); 3.System.out.println("the month first day is "+formats.format(firstDay)); java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-01"); java.util.Date firstDay=new java.util.Date(); System.out.println("the month first day is "+formats.format(firstDay));
取当月的最后一天:
Java代码 1. 2.Calendar cal = Calendar.getInstance(); 3.int maxDay=cals.getActualMaximum(Calendar.DAY_OF_MONTH); 4.java.text.Format formatter3=new java.text.SimpleDateFormat("yyyy-MM-"+maxDay); 5.System.out.println(formatter3.format(cal.getTime())); Calendar cal = Calendar.getInstance(); int maxDay=cals.getActualMaximum(Calendar.DAY_OF_MONTH); java.text.Format formatter3=new java.text.SimpleDateFormat("yyyy-MM-"+maxDay); System.out.println(formatter3.format(cal.getTime()));
求两个日期之间相隔的天数:
Java代码 1.java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); 2.java.util.Date beginDate= format.parse("2007-12-24"); 3.java.util.Date endDate= format.parse("2007-12-25"); 4.long day=(date.getTime()-mydate.getTime())/(24*60*60*1000); 5.System.out.println("相隔的天数="+day); java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); java.util.Date beginDate= format.parse("2007-12-24"); java.util.Date endDate= format.parse("2007-12-25"); long day=(date.getTime()-mydate.getTime())/(24*60*60*1000); System.out.println("相隔的天数="+day);