Java Data Type How to - Create new Calendar from Parsed date and time








Question

We would like to know how to create new Calendar from Parsed date and time.

Answer

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*from   w w w.  j  a  va  2s  .  co m*/
public class Main {
  public static void main(String[] args) throws Exception {
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
    Date workDate = simpleDateFormat1.parse("2011-11-27");

    Calendar workCalendar = Calendar.getInstance();
    workCalendar.setTime(workDate);
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
    Calendar time = Calendar.getInstance();
    time.setTime(simpleDateFormat2.parse("06:00:00"));
    workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
    workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
    workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
    
    Date newWorkDate = workCalendar.getTime();
    
    SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
        "yyyy-MM-dd hh:mm:ss");
    System.out.println(simpleDateFormat3.format(newWorkDate));
  }
}