Java Hour Calculate addHours(int date, int hours)

Here you can find the source of addHours(int date, int hours)

Description

add Hours

License

Apache License

Declaration

public static String addHours(int date, int hours) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {

    public static String addHours(int date, int hours) {
        try {/*  ww w  .ja  v  a 2 s . c o  m*/
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(format.parse(String.valueOf(date)));
            cd.add(Calendar.HOUR_OF_DAY, hours);
            return format.format(cd.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String addHours(String date, int hours, String pattern) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(format.parse(date));
            cd.add(Calendar.HOUR_OF_DAY, hours);
            return new SimpleDateFormat(pattern).format(cd.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static Date add(int days) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_YEAR, days);
        return now.getTime();
    }

    public static String add(int days, String pattern) {
        Date date = add(days);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static String add(int date, int days) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(format.parse(String.valueOf(date)));
            cd.add(Calendar.DAY_OF_YEAR, days);
            return format.format(cd.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String add(String date, int days, String pattern) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(format.parse(date));
            cd.add(Calendar.DAY_OF_YEAR, days);
            return new SimpleDateFormat(pattern).format(cd.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. addHour(String now)
  2. addNHours(Date date, int hours)
  3. diffHour(String day1, String day2)
  4. getBothTime(String startTime, int hours)
  5. getCurrHourDate()