2

I'm new to joda-time and I didn't find anywhere examples to do some simple things.

I want to make an object where to save a time value read from a table in a database (a java.sql.Time - e.g. "18:30:00") I don't care about time zone, so I think that I need LocalDate. But the problem is that I couldn't create a LocalDate object based on that Time object.

I tried with no success LocalDate.fromDateFields(), DateTimeParser.parseInto(), DateTimeParser.parseDateTime().

EDIT: I should have used LocalTime. These work:

java.sql.Time time = Time.valueOf("18:30:00");
LocalTime lt1 = LocalTime.fromDateFields(time);
LocalTime lt2 = new LocalTime(time);
True Soft
  • 8,675
  • 6
  • 54
  • 83
  • `org.joda.time.LocalDate` represents a date, `java.sql.Time` represents a time. What meaningful conversion would you expect to get from that? – skaffman Dec 14 '09 at 14:24
  • I saw that `YearMonthDay` and `TimeOfDay` were classes where you don't need all the datetime fields (partial). But when I wanted to use them, there were deprecated and it said use `LocalDate` and `LocalTime`. Now I see that I should have used `LocalTime`. But it doesn't work with this neither. – True Soft Dec 14 '09 at 14:37
  • How would one go the other around. I am trying to convert fom LocalTime to sql time, but I noticed the getMillis()* functions of LocalTime return ints. I want to void having to shuttle it through DateTime. – Dark Star1 Apr 30 '12 at 09:24
  • @DarkStar1: I think `getMillisOfDay()` would work, if you only need the time fields. They return ints because there are only 86,400,000 millis in a day. – True Soft May 01 '12 at 13:10

1 Answers1

4

According to the documentation, you should be able to construct a LocalDate directly by passing it a java.util.Date as the sole constructor argument. Since a java.sql.Time extends java.util.Date, you should be able to

final LocalDate ld = new LocalDate(mySqlTime);

This works for me:

System.out.println(new LocalDate(Time.valueOf("18:30:00")));

On the other hand, it's not a meaningful thing to do, since you'll always get January 1, 1970. But I imagine you know what you're doing.

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
  • I already tried `LocalDate ld = new LocalDate(Time.valueOf("18:30:00"));` and it gives `java.lang.UnsupportedOperationException` – True Soft Dec 14 '09 at 14:29
  • Only somewhat related, but using the `LocalDate` constructor with values from a database you have to be careful: `null` values will be converted into the current date (which may very well not be what you want). – Ingo Bürk Apr 14 '14 at 12:28