用Calendar来完成获取年份、月份 、日以及按月加等功能

      由于Date  timestamp中的getYear、getMonth等方法都已过时,不能用了,现在都替换成用Calendar去实现,且Calendar功能更加丰富。

一、用Calendar来获取年月日

public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        String time1 = "2015-11-12 12:15:13";
        Timestamp starTimestamp = Timestamp.valueOf(time1);//time1也可以是Date
        System.out.println(starTimestamp);
        calendar.setTime(starTimestamp);
        int i = calendar.get(Calendar.YEAR);
        System.out.println(i);
        
        String time2 = "2018-11-12 12:15:13";
        Timestamp starTimestamp2 = Timestamp.valueOf(time2);
        System.out.println(starTimestamp2);
        calendar.setTime(starTimestamp2);
        int j = calendar.get(Calendar.YEAR);
        System.out.println(j);
        
        int month = calendar.get(Calendar.MONTH) + 1;    
        int day = calendar.get(Calendar.DATE);    
        int hour = calendar.get(Calendar.HOUR_OF_DAY);    
        int minute = calendar.get(Calendar.MINUTE);    
        int second = calendar.get(Calendar.SECOND);    
        int dow = calendar.get(Calendar.DAY_OF_WEEK);    
        int dom = calendar.get(Calendar.DAY_OF_MONTH);    
        int doy = calendar.get(Calendar.DAY_OF_YEAR);
    }

      注意:Timestamp starTimestamp2 = Timestamp.valueOf(timestamp)中,timestamp类型也可以是java.util.Date类型,java.sql.Date和java.sql.timestamp都继承了java.util.Date。

二、可以用Calendar来计算

Calendar calendar = Calendar.getInstance();        

calendar.setTime(tbProRating.getRatingStart());

calendar.add(Calendar.MONTH, tbProRating.getRatingPeriod());

Timestamp ratingEnd = new Timestamp(calendar.getTime().getTime());

Calendar.MONTH 按月加

Calendar.DAY_OF_MONTH 按天加


你可能感兴趣的:(java)