怎么把2007-12-1转换成2007年12月?还有一个问题,如何知道如果知道某年,某月,怎么知道这个月的最后一天?
例如2007年12月,最后一天是31.
2007年2月,最后一天是28.

解决方案 »

  1.   

    public static String date2String(Date date) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        return sdf.format(date);
    }关于后面那个很简单public statci String lastDayOfMonth(int yyyy,int month) {
        Date newDate = new Date(yyyy,month,1);
        Calendar temp = Calendar.getInstance(TimeZone.getDefault());
        temp.setTime(newDate );
        temp.add(temp.MONTH, 1);
        temp.add(temp.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(temp.getTime());
    }核心思想 就是把给定的年月 转换成当月的1号,然后加1个月,日期就变成了下月的1好,然后减1天就成了月末日了。记得C#有更加简单的办法。
      

  2.   


    import java.text.SimpleDateFormat;
    import java.util.Date;
    class Test
    {
    public static void main(String [] args)throws Exception
    {
    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月");
    Date d=sdf1.parse("2007-12-1");
    System.out.println(sdf2.format(d));
    }
    }
      

  3.   

    第一个:
    String str = "2007-12-1";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    try {
    Date date = format.parse(str);
    format = new SimpleDateFormat("yyyy年MM月");
    System.out.println(format.format(date));
    } catch (Exception e) {
    e.printStackTrace();
    }
      

  4.   

    我也就是这样做的。可是怎么报错啊?郁闷Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Unhandled exception type ParseException at test.TestDate.main(TestDate.java:17)
      

  5.   

    支持1楼, 参见:        Calendar temp = Calendar.getInstance();
            try {
                temp.setTime(new SimpleDateFormat("yyyy/MM/dd").parse("2007/12/1"));
            } catch (ParseException ex) {
                ex.printStackTrace();
            }
            temp.add(temp.MONTH, 1);
            temp.add(temp.DATE, -1);
            System.out.println("output:" + new SimpleDateFormat("yyyy/MM/dd").format(temp.getTime()));
    另:new   Date(yyyy,month,1); 这样的用法jdk1.5已不推荐使用.
      

  6.   

    发现问题了,原来没有catch异常
      

  7.   

    Calendar c = GregorianCalendar.getInstance();
    System.out.println(c.getActualMaximum(Calendar.DATE));