增加日期(时间戳)从数据库获得1年

时间:2014-09-12 05:13:04

标签: java date

我从数据库通过bean获取日期值。我想将数据库中的日期增加1年。 有人可以告诉我,我该怎么做? 这是我到目前为止所做的。

    if (reviewDate != null || !(reviewDate.equals("0"))) 
                {    
                    //convert reviewDate string to date
                    Date currentDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(reviewDate);
                    System.out.println("currentDate = "+currentDate);

                    //get the current year
                    int currentMonth = currentDate.getMonth();
                    int currentDay = currentDate.getDate();
                    long currentYear = currentDate.getYear();
                    long currentTime = currentDate.getTime();   
                    System.out.println("current month="+currentMonth);
                    System.out.println("current day="+currentDay);
                    System.out.println("current year="+currentYear);
                    System.out.println("current time="+currentTime);

                    Date newDate = null;

                    //increment year
                    currentYear = currentYear+1;
                    System.out.println("current year after increment="+currentYear);

                    //add this to currentDate and assign to newDate
                    reviewDate = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentTime;

                    System.out.println("ReviewDate=" + reviewDate);
                } 

我的输入是 - 04/22/1980 11:30:20 我的输出应该是 - 04/22/1981 11:30:20

但是,我得到3/22/81/325279822000

我想我不能使用日历,因为我不想按当前日期递增。有人可以为我建议一个有效的解决方案吗?

2 个答案:

答案 0 :(得分:3)

你可以试试这种方式

 String rDate="04/22/1980 11:30:20"; // your received String date
 DateFormat df=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");// date format
 Date date=df.parse(rDate);// parse String to date
 Calendar calendar=Calendar.getInstance();
 calendar.setTime(date); // set calender instance to date value
 calendar.add(Calendar.YEAR,1); // add one year to current
 System.out.println(df.format(calendar.getTime()));

Out put:

 04/22/1981 11:30:20

关于Java Calendar

答案 1 :(得分:2)

以下是java.time的Java 8解决方案:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class SO25801191 {

    public static void main(String[] args) {
        System.out.println(getDateAsStringIncrementedByYear("04/22/1980 11:30:20", "MM/dd/yyyy HH:mm:ss", 1));
    }

    private static String getDateAsStringIncrementedByYear(String inputDateStr, String pattern, long yearsToIncrement) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime dateTime = LocalDateTime.parse(inputDateStr, formatter);      
        return dateTime.plusYears(yearsToIncrement).format(formatter);
    }
}