Java Data Type How to - Convert normal date to date with current time








Question

We would like to know how to convert normal date to date with current time.

Answer

/*from   ww w.ja v a  2s.c  o m*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void previousDateString(String dateString)
      throws ParseException {
    DateFormat inputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    DateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    Calendar now = Calendar.getInstance();
    Calendar calendar = Calendar.getInstance();
    Date myDate = inputDateFormat.parse(dateString);
    calendar.setTime(myDate);
    calendar.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY));
    calendar.set(Calendar.MINUTE, now.get(Calendar.MINUTE));

    String output = outputDateFormat.format(calendar.getTime());
    System.out.println(output);
  }

  public static void main(String[] args) throws ParseException {
    String dateString = "10-06-2014";

    previousDateString(dateString);

  }

}

The code above generates the following result.