1. 程式人生 > >java實現時間相加減

java實現時間相加減

程式碼


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by qqg on 2017/12/26.
 */
public class Times {
    public String addTime(Date date,int hour){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY,hour);
        SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /*try { Date date1 = sdf.parse(sdf.format(calendar.getTime())); return date1; } catch (ParseException e) { e.printStackTrace(); }*/ return sdf.format(calendar.getTime()); } public static
void main(String[] args) { Times times = new Times(); Date date = new Date(); System.out.println(times.addTime(date,-8)); } }

傳入的引數為正時是加,負時是減。