m.o m.o - 5 months ago 18
Java Question

Java pass formatted Calendar object to method

I want to pass a formatted timestamp to a method using Calendar (using Java 1.6.0_22). I have a method with this signature:

public void setTimestamp(Calendar param0);


To get the timestamp, I did this:

Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_WEEK),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));


I want it formatted in this way:

yyy-MM-ddTHH:mm:ss


Then pass it to the method. I can't change the method as I didn't make it. How can I achieve this?

Answer

What you need is convert the string to Date first, then set it to Calendar.

    String input = "2016-05-11T14:44:09";
    java.util.Date date = new java.text.SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss").parse(input);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    obj.setTimestamp(cal);
Comments