1

I need a GregorianCalendar from String "day/month/year" - 1/12/2014 for example. Anyone can help? advice? Or if this is hard to do, mayby Yu have a better idea?

hetmanJIIIS
  • 106
  • 1
  • 11
  • See javadoc for `SimpleDateFormat` – fge Feb 19 '14 at 20:10
  • Use [Joda-Time](http://www.joda.org/joda-time/) – Math Feb 19 '14 at 20:11
  • Or if you want to go overboard, you can look into JodaTime: http://www.joda.org/joda-time/ :) – Josh Feldman Feb 19 '14 at 20:11
  • That looks like January 12th to me :) – Jason Sperske Feb 19 '14 at 20:11
  • 1
    Also I wouldn't consider JodaTime overboard. – Jason Sperske Feb 19 '14 at 20:12
  • 1
    If this was a program that truly had to complete this one task I can understand how a library can feel overkill but if the program is meant to work with time in general the JodaTime will painless solve for problems you don't realize you will have until there is too much code invested in Java's infernal broken calendar system. – Jason Sperske Feb 19 '14 at 20:19
  • FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 05 '18 at 19:36

1 Answers1

2

Try with SimpleDateFormat to parse your String to a date. Set this date to your GregorianCalendar instance:

String dateStr = "1/12/2014";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);
Calendar cal = new GregorianCalendar();
cal.setTime(date);

This can be achieved using joda-time as well:

String dateStr = "1/12/2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dateTime = formatter.parseDateTime(dateStr);
GregorianCalendar gc = dateTime.toGregorianCalendar();
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 05 '18 at 19:37