-1

Possible Duplicate:
How to convert a date String to a Date or Calendar object?

How could I do something like this

GregorianCalendar cal = new GregorianCalendar("2012-08-02 12:04:03");

or

Calendar cal = Calendar.getInstance();
cal.setDateTime("2012-08-02 12:04:03");

NOTE: The code snippets above are not actually possible, I would like to mock that behavior.

Further Clarification

Suppose I have a date and time string like "2012-08-02 12:04:03". Is there an efficient way of getting this information into a Calendar object without manually breaking it up into month, year, and day strings then converting them to integers then calling set(Calendar.HOUR) etc?

Currently, I have a form that takes as input the year, month, hour, day, and so on and I pass those individually into a calendar object but it would be nice if I could use a single date and time string like "2012-08-02 12:04:03"

Community
  • 1
  • 1
Usman Mutawakil
  • 4,993
  • 9
  • 43
  • 80

3 Answers3

1

You have to use SimpleDateFormat which gives you a Date object. With that Date object you can initialize your Calendar

Kai
  • 38,985
  • 14
  • 88
  • 103
  • I know you can use SimpleDateFormat to format the output of Calendar object but how would you use it configure the input? – Usman Mutawakil Sep 27 '12 at 13:06
  • See the [parse()](http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse%28java.lang.String,%20java.text.ParsePosition%29) method. – Kai Sep 27 '12 at 13:09
1
    String dateString=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("2012-08-02 12:04:03");
            Calender cal = Calender.getInstance();
            cal.setTime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(dateString).getTime());

wrap it around try catch though as the parse method would throw ParseException. and study the link provided by @user714965

Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

Use .parse() method to convert the String to Date object:

String dateString=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("2012-08-02 12:04:03");

getInstance() will create an instance of one of the Subclass of the abstract Calendar class:

Calender cal = Calender.getInstance();

setTime() will take a Date object:

cal.setTime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").fomat(dateString).getTime());

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75