I want to convert a LocalTime object to a java.sql.Time object.
java.sql.Time time = new java.sql.Time(new LocalTime(1,0,0,0).getMillisOfDay());
System.out.println(time); //20:00:00
The above code, instead of creating a Time object with a value equal to 01:00:00, creates an object with a time of 20:00:00. The local time is eastern time.
What steps should I take?
Time(..) accepts a timestamp starting from 1970. So you should pass that:
new Time(new LocalTime(...).toDateTimeToday().getMillis())
I consider the currently accepted answer to be incorrect. Although java.sql.Time implies that its date fields are set to 1970-1-1, this is not true. If you use the conversion
new java.sql.Time(new LocalTime(...).toDateTimeToday().getMillis())
then the internal millesecond representation of the java.sql.Time object will reflect today's date. This leads to unexpected behavior when comparing java.sql.Time objects.
Comparisons are performed on the millisecond value, and if the underlying dates are different, the time fields are irrelevant to the comparison result
A better method, is to explicitly work with the time-fields, using the deprecated constructor and methods in java.sql.Time:
LocalTime localTime = new LocalTime(1,0,0,0);
java.sql.Time sqlTime = new java.sql.Time(localTime.getHourOfDay(), localTime.getMinuteOfHour(), localTime.getSecondOfMinute())
Similarly, in the other direction
java.sql.Time sqlTime = new java.sql.Time(1,0,0);
LocalTime localTime = new LocalTime(sqlTime.getHours(), sqlTime.getMinues(), sqlTime.getSeconds());
This seems like a hole in the Joda Time API. Right now getLocalMillis() is protected, but that's exactly the method I'd want to use.
However, if you want to avoid deprecated methods, you can figure out time on January 1, 1970:
LocalTime lt = new LocalTime(1, 23, 45, 678);
long millis = lt.toDateTimeToday().withDate(1970, 1, 1).getMillis()
java.sql.Time time = new java.sql.Time(millis);
This seems to work. Interestingly, I tried figuring out the millis by multiplying the values of the fields out. That produced the right long value, but when I passed it to the Time constructor, something weird happened with the time zone. (I think, at least. The Time value ended up five hours before the value I passed in, and I'm on Eastern Daylight Time, so I think that's what happened.)
i found another way to convert the java.time.LocalTime to java.time.LocalTime
LocalTime localTime = LocalTime.now();
Time time = Time.valueOf(localTime);
Related
I'm trying to convert a java.time.LocalTime object to java.util.Date but can't find any suitable method. What's the correct way to do this?
Is there any reason why java doesn't seem to ship with a built-in direct conversion method?
To possible duplicates:
How to convert joda time - Doesn't work for me, probably I'm missing some "joda" libraries?
How to convert Date to LocalTime? - This adresses conversion the other way around.
LocalTime actually can't be converted to a Date, because it only contains the time part of DateTime. Like 11:00. But no day is known. You have to supply it manually:
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
Here's a blog post which explains all the conversions between the new and the old API.
There's no simple built-in conversion method, because these APIs approach the idea of date and time in completely different way.
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
From :
http://blog.progs.be/542/date-to-java-time
I added the data (hour, minute, second) one by one (from localtime to date):
reta.setHours(vol.getRetard().getHour());
reta.setMinutes(vol.getRetard().getMinute());
reta.setSeconds(vol.getRetard().getSecond());
Note :
reta: Date veriabble ;
vol.getRetard (): localtime variable
As others have said, it’s a problematic question in that a LocalTime and a Date really represent quite different and almost unrelated concepts. A LocalTime is a time of day without time zone, such as 19:45 (or 7:45 PM). A Date is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones.
I believe that the conventional way of misusing (indeed) a Date for an hour of day is setting it to that time of day on January 1, 1970 in the default time zone of the JVM. This practice carries all of the liabilities already mentioned. In particular the JVM default time zone setting can be changed at any time from another part of your program or any other program running in the same JVM. This means that a completely unrelated program may suddenly cause your Date to indicate a different time of day than the one you had initialized it to.
There’s nothing better we can do, so here goes:
LocalTime time = LocalTime.of(11, 0);
Instant timeOnEpochDayInDefaultTimeZone = LocalDate.EPOCH
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant();
Date oldfashionedDateObject = Date.from(timeOnEpochDayInDefaultTimeZone);
System.out.println(oldfashionedDateObject);
In my time zone output from this snippet is:
Thu Jan 01 11:00:00 CET 1970
Here is another approach:
We can add a LocalDate to the LocalTime in order to make it a LocalDateTime and then convert it to Date using the valueOf method of java.sql.Timestamp like this:
LocalTime localTime = LocalTime.now();
Date date = java.sql.Timestamp.valueOf(localTime.atDate(LocalDate.now()));
As #Dariusz said, we cannot convert LocalTime to Date directly as it contains only time part but Date must contain all the value along with the timeZone.
In order to get the date part, we can use LocalDate.now(). It will give us LocalDate object with today's date.
Now, we have both LocalDate and LocalTime, we can now use the LocalDateTime.of(date: LocalDate, time: LocalTime) or localTime.atDate(date: LocalDate) to get the LocalDateTime object.
And now we can convert the LocalDateTime to Date using below kotlin extension function.
fun LocalDateTime.toDate(): Date {
return Date.from(this.atZone(ZoneId.systemDefault()).toInstant())
}
Regarding jFreeChart's Millisecond,
How can I get a java.util.Date object from a Millisecond instance?
From the docs, it only seems possible to subtract the milliseconds within Millisecond.
Since a Millisecond object is constructed like so:
Millisecond ms = new Millisecond(
millisec,
second,
minute,
hour,
day,
month,
year);
I should be able to extract a valid Date object as well.
Edit
I need a Date object that gives back the exact time up to the millisecond accurate.
Does .getStart() provide this?
[ANSWER]: YES
Millisecond is like any other RegularTimePeriod in JFreeChart, so you can just
Date d = ms.getStart();
or
Date d = ms.getEnd();
depending on whether you want a date referring to the beginning or the end of your millisecond (same value either way).
See The JFreeChart API for more info.
EDIT: Adding code here since comments kill formatting:
Millisecond ms = new Millisecond();
System.out.println(ms.getStart().getTime());
System.out.println(ms.getEnd().getTime());
will print the same millisecond twice.
As far as I can see the Millisecond Class represents the time period of a millisecond and I'd assume the the getStart and getEnd Methods inherited from RegularTimePeriod return (nearly) the same Date of which one is one you're looking for.
(my answer was late) Perhaps you could use this code:
java.util.Date date = new java.util.Date(freeMillis.getMillisecond());
edit: scrap that, freeMillis.getMillisecond() returns just a millisecond part.
I'm trying to create a java.sql.Time object to query time types in an SQL database, but I'm using joda to parse the string that I receive.
I've tried a few different approaches. This is my most recent.
protected Time startTime = null;
protected static final String dateFormat = "HH:mm:ssZ";
protected static final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
public TimeBetweenFilter(String fieldName, String type, String value) {
super(fieldName, type, value);
String [] times = value.split("\\|");
if(times.length == 2 && !times[0].isEmpty() && !times[1].isEmpty()){
try{
LocalDateTime current = LocalDateTime.now();
LocalDateTime timeFromEpoch= new LocalDateTime(formatter.parseDateTime(times[0]));
startTime = new Time(timeFromEpoch.withDate(current.getYear(), current.getMonthOfYear(), current.getDayOfMonth()).toLocalTime().toDateTimeToday().getMillis());
}catch (Exception e){
...
}
But the output is always 1 hour behind the input received. For instance, if the input is 10:30:00 in UTC, startTime should be 4:30:00 local time. But instead I get 3:30.
Solved
DateTime beginning = new DateTime(DateTimeZone.UTC).toDateMidnight().toDateTime().plus(DateTime.parse(times[0], formatter).getMillis());
startTime = new Time(beginning.getMillis());
Creates a new date, this morning at midnight with time zone UTC, then adds the UTC time of day in milliseconds. Then it's converted to a java.sql.Time object.
A LocalDateTime doesn't logically have any time zone or DST information. That's the whole point - it's "local" but not to any specific time zone. Two people in different time zones might both wake up at the same local date/time, but that doesn't mean they're the same instants.
If you need a type which includes a time zone, you should be using DateTime.
EDIT: Okay, one approach is to take "today in the local time zone", parse the time to a LocalTime, combine the two to form a LocalDateTime, convert that to a DateTime in UTC, then convert that DateTime to the local time zone instead. The difficulty is that the end dates may not be the same, in which case you may need to add or subtract a day. That could then change the time of day due to DST changes, which makes it harder still. There are likely to be nasty corner cases to consider.
It feels like your requirement is odd to start with though - it's odd to have just a time which is in UTC, which you want to use in a date/time in the local time zone. Perhaps if you gave some more context, that would help.
Given millis since epoch, I want an instance with the fields Month, Date, Year filled out, with the hour minute seconds set to some default values.
What is an efficient way to do this?
I know that there are sql ways to do it but is there a way to do it in Java?
Just use:
new Calendar(new Date(msSinceEpoch));
where the ms is a long value.
Use either LocalDate or DateMidnight in the Joda-Time API. The differences are explained in the javadocs.
Note that in order to truncate a point in time (some millis since epoch) to a specific calendar day, you might want to specify when midnight happened, or else you'll end up with midnight in the system's timezone. For example, you might call the LocalDate(long, DateTimeZone) constructor instead of the LocalDate(long) constructor.
Or, if you'd rather not have a JODA dependency, use DateFormat:
Date thisDate = new SimpleDateFormat("yyyy-MMM-dd").parse("2011-Jun-29");
Per the javadocs, you can easily create a Date from a long:
long value = System.currentTimeMillis();
Date thisDate = new Date(value);
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);
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.