/**
* Calendar提供了可以针对不同时间分量(时间单位)
* 单独设置值的相关方法
* void set(int field,int value)
* 对指定的时间分量设置指定的值
*/
public class CalendarDemo2 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println(calendar); calendar.set(Calendar.YEAR, 2008); System.out.println(calendar.getTime()); calendar.set(Calendar.MONTH, Calendar.AUGUST); System.out.println(calendar.getTime()); /* * 设置日 */ calendar.set(Calendar.DAY_OF_MONTH, 8); System.out.println(calendar.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 20); calendar.set(Calendar.MINUTE, 8); calendar.set(Calendar.SECOND, 8); System.out.println(calendar.getTime()); calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); System.out.println(calendar.getTime()); // calendar.set(2008, 7, 8); // System.out.println(calendar.getTime()); Date date = calendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH点mm分ss秒"); String dateStr = sdf.format(date); System.out.println(dateStr); } }
/**
* 获取某一个时间分量所对应的值:
*int get (int field)
*
*/
public class CalendarDemo3 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1; int days = calendar.get(Calendar.DATE); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int sec = calendar.get(Calendar.SECOND); System.out.println(year+"年"+""+month+"月"+days+"日"+hour+"时"+minute+"分"+sec+"秒"); int weekday = calendar.get(Calendar.DAY_OF_WEEK); String[] week = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; System.out.println(week[weekday-1]); int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); System.out.println("当月有"+max+"天"); int maxOfYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); System.out.println("当年有"+maxOfYear+"天"); } }
/**
* void add(int field,int value)
* 给定的时间分量累加给定的值,若value是负数,则是做减法操作
*/
public class CalendarDemo4 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 3); calendar.add(Calendar.MONTH, 2); calendar.add(Calendar.DAY_OF_YEAR, 25); calendar.add(Calendar.DAY_OF_YEAR, -3); System.out.println(calendar.getTime()); Date date = calendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = sdf.format(date); System.out.println(str); } }
时间: 2024-10-11 01:44:19