Java Date Create addTimeToDate(Date date, Date time)

Here you can find the source of addTimeToDate(Date date, Date time)

Description

Adds specified time of day to a date.

License

Open Source License

Parameter

Parameter Description
date The date.
time The time.

Return

Date field with combined (date, time) set.

Declaration


public static Date addTimeToDate(Date date, Date time) 

Method Source Code


//package com.java2s;
/*   Please see the license information at the end of this file. */

import java.util.*;

import java.text.*;

public class Main {
    /**   Date formatter for dates and times in format e.g. 02/06/02 10:32 AM. */

    static private final SimpleDateFormat dateFormatter1 = new SimpleDateFormat("MM/dd/yy hh:mm aa");
    /**   Date formatter for dates in format e.g. 2/6/2002. */

    static private final SimpleDateFormat dateFormatter2 = new SimpleDateFormat("M/d/yyyy");
    /**   Timer formatter for dates in format hh:mm aa. */

    static private final SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm aa");

    /**   Adds specified time of day to a date.
     */*from  w w  w  .j  av a  2  s. c o  m*/
     *   @param      date   The date.
     *   @param      time   The time.
     *
     *   @return      Date field with combined (date, time) set.
     */

    public static Date addTimeToDate(Date date, Date time) {
        String dateAndTime = formatDateNoTime(date) + " " + formatTime(time);

        ParsePosition pos = new ParsePosition(0);
        Date result = dateFormatter1.parse(dateAndTime, pos);

        if ((result != null) && (pos.getIndex() < dateAndTime.length()))
            result = null;

        return result;
    }

    /**   Formats a date as (for example) "2/6/2002".
     *
     *   @param   date      The date.
     *
     *   @return            The formatted date.
     */

    public static String formatDateNoTime(Date date) {
        return dateFormatter2.format(date);
    }

    /**   Formats a time as (for example) "10:32 AM".
     *
     *   @param   date      The time.
     *
     *   @return            The formatted time.
     */

    public static String formatTime(Date date) {
        return timeFormatter.format(date);
    }
}

Related

  1. add24HtoDate(Date date)
  2. buildDate(int y, int m, int d)
  3. buildDate(String dateAsString)
  4. buildDateFormat(final String pattern)
  5. buildDatetime(Date datePart, Date hourMinutePart)