how can i get a date object that has only time - java

I have a field "startdate" which is of type DATE.I want to get only time in this field and that too in "yyyy-mm-dd" format.I tried too many things but can't get only the time in a DATE type object .I have to store it in database.
Any helps???

The class Date represents a specific instant in time, with millisecond
precision.
(Date in the manual)
So a Date object represents a specific moment in time (i.e., including the date). You are trying to put into it a time of day, which is an infinite set of moments: one fore each day.
You will need to pick a specific day yourself. Pick any day you like, since you don't need it anyway.
Or you can use the subclass java.sql.Time which always uses January 1, 1970 as the date part.

Related

Do I have a way to avoid re-creating lots of String objects?

My project uses Javascript and Java (Android) for the client and Java for the backend.
When I started working on my project, I stored dates as days from epoch (long) and all was good. I then found out that my project doesn't work well with timezones. Suddenly dates were +1 -1 days off. Depending on the client's location in the world.
After a short investigation, I saw that the foolproof way to avoid it was to store the dates as String yyyy-MM-ddT00:00 so when using the Javascript's new Date(dateStr), it creates it correctly and all was good. Ofcourse I could store the dates as yyyy-MM-dd and just send it to the client as yyyy-MM-ddT00:00 but that won't solve the question I have.
After that, I was wondering whether Java (backend) is handled correctly. I use LocalDate when I want to "play" with dates and LocalDate.parse doesn't like yyyy-MM-ddT00:00 format, instead it works with yyyy-MM-dd so whenever I needed dates, I did LocalDate.parse(dateStr.substring(0,10)). LocalDateTime does work with yyyy-MM-ddT00:00 but I don't need the time part and it had its own issues, which I don't remember what they were at the moment.
So now I have a lot of String manipulation (inside loops) that actually creates more String objects. One can say it's not that much of a stress and I shouldn't pay attention to that but I want to make sure I'm not missing something and maybe there's another way (maybe silly enough that I've missed) to overcome this.
Thanks
Update: The events are stored from a different source and only the date itself is important so if an event happened on 2020-06-17, this is the date all users should see, no matter where they are.
I'm using new Date(dateStr) in Javascript. If dateStr is 2020-06-17, the date object uses the client's timezone and the date might be +-1 depending on the client's timezone. If dateStr is 2020-06-17T00:00 then the date object is created as expected no matter where the client is located.
Assuming the above, which I hope is clearer now, creating String objects over and over again is a memory stress that I should consider or is it something Java handles with no problem and I shouldn't worry about this?
My question was closed and I was told to edit it to be more focused. After editing my question, how can I re-open my question to answers?
As you have discovered, storing dates in terms of days since some epoch only works if everyone who uses your system is using the same time zone. If two different users in different time zones have a different idea about the date on which some event occurred (e.g., the person in New York says that the system crashed on Sunday night, but the the person in Hong Kong says it crashed on Monday morning), then you have to store the time zone in which the event occurred in order to show the date of that event accurately.
But if that's the situation you're in, why not just store the time zone along with the date? There's no compelling reason to combine the date and timezone into a string.
When you parse a ISO-formatted timestamp into a LocalDate using only the first 10 characters, be aware that you're losing the time zone information. Implicitly the LocalDate that you get is in the time zone of the original timestamp. So if the original timestamp is New York time, and you take the date part and add 1 day, then you'll get the next day in the New York time zone. But if you then take the date from a second timestamp, you can't compare it to the date you got from the first timestamp, in terms of determining if it represents the "same day." You can only test for "same day" if both dates are implicitly in the same time zone.
UPDATE
After reading your additional comments, I realize that what's happening is this. You have a date stored in your database, like 2020-06-15. You send that to the UI as the string '2020-06-15' and then do new Date('2020-06-15') and then you're surprised when you render the date in the UI and get June 14!
This is the transformation that happens:
The string '2016-06-15' gets parsed into a JavaScript Date representing midnight UTC on the June 15.
When you render the date, it gets converted into a string using the browser's local time zone, which (if you're in the United States) will give you June 14, because at midnight UTC on June 15 it's still June 14 in all time zones west of Greenwich.
You discovered that if you make the string "2020-06-15T00:00" that it works, because now JavaScript uses the browser's local time zone to parse the string. In other words, this string means midnight local time, not UTC, on June 15. So now the sequence is:
'2020-06-15T00:00' gets parsed using the local time zone and becomes June 15 4:00AM UTC.
When you render the date, it gets converted back to local time and is rendered as June 15.
The easiest way to avoid all this messiness is just to send the regular date string '2020-06-15' to the UI and render it using DateTimeFormat, specifying the time zone as UTC:
new Intl.DateTimeFormat('en-US', {timeZone: 'UTC'}).format(d)
Since dates in JavaScript are always UTC, and you're asking DateTimeFormat to output the date in UTC, no date shift occurs.
You could also use the Date methods getUTCFullYear, getUTCMonth, etc. to get the date components and format them however you like.
Once you're no longer sending dates back and forth with "T00:00" appended, you can just use LocalDate on the Java side.
Don't spend even a second worrying about the time required to manipulate strings. Think about the incredible amount of string manipulation that is necessary to build even a simple web page. A few more strings here and there isn't going to make a difference.

Why are diferences between get milliseconds from LocalDateTime and Date from Calendar?

I'm porting my code from Timestamp to LocalDateTime, when I made a tests to get a milliseconds from LocalDateTime I saw a difference result from get it using Calendar and Date.
This is my "test":
System.out.println(LocalDateTime.of(2016,5,19,14,8,0).toInstant(ZoneOffset.UTC).toEpochMilli());
System.out.println(Timestamp.valueOf(LocalDateTime.of(2016,5,19,14,8,0)).getTime());
Calendar c = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("UTC")));
c.set(2016,5,19,14,8,0);
System.out.println(c.getTime().getTime());
I don't understand why the difference between those.
The result of your test is:
1463666880000
1463659680000
1466345280067
Each value is in milliseconds.
The difference between the first two values is exactly two hours. It is because in the first line you set UTC timezone and in the second line you didn't set anything, so it is in local timezone (and indeed, I am currently in UTC+2).
The difference in the first and the third values - apart from the millisecond part - is exaclty one month. It is because LocalDateTime.of() method expects the month argument represented from 1-12, but Calendar.set() expects month argument represented from 0-11. So in the third line you actually set 06/19/2016.

DateTime to java.sql.timestamp conversion is adding +1 hour

I am calling my rest api with following url localhost:8080/api/2016-05-30T10:30:00-05:00/3
The api receives date as String and then convert it into jodatime datetime object like dateTime = DateTime.parse(date); ... debugging this code shows that its resulting in expected value.
However, when i am converting this date to java.sql.timestamp like Timestamp ts = new Timestamp(dateTime.getMillis()); ... the resulting time is 2016-05-30 11:30:00.0 ... why is it adding +1 hour to the time and whats the proper way to convert ?
SOME BACKGROUND
I have saved the time as timestamp in sql table. with timezone (as a string +4:00 or -5:00 for example) in a separate column.
I would receive an ISO8601 time in my url path parameter and based on that I have to fetch the record from db. For that, I will be using two comparison. 1 to match the time and 2 to match the timezone.
The ISO 8601 states that
... the time in New York in winter is UTC−05:00
So it seems daylight saving time is not included in the date string, which means what you get is the correct time, as per the defined timezone (-05:00). New York summer time should be -04:00, as DST is not part of ISO 8601.
You could add an extra DST column in your database or add it as a parameter, or go through the process of checking whether you are in DST, which varies country to country (e.g. Qatar does not uses it) and year by year (e.g Russia has abandoned DST a few years ago), so it's not a viable option...
EDIT:
Another option would be for you to test if the Timezone is currently in DST, as indicated in another answer. You could then apply the -1h offset.
Note that Joda has a minusHours() method you can use, if inDaylightTime() returns true.

SimpleDateFormat + java.sql.Timestamp in Jasper Reports

I have a timezone-delicate report in Jasper and I can't really seem to figure out how to show a few dates relative to a timezone.
I have a view which returns dates with the following format:
"2015-03-02 11:45:00+01"
"2015-03-02 23:59:59+01"
"2015-03-03 00:00:00+01"
"2015-03-03 08:00:00+01"
"2015-03-03 09:20:00+01"
"2015-03-03 11:00:00+01"
"2015-03-03 09:00:00+01"
"2015-03-03 09:30:00+01"
etc (notice the +01 at the end)
In my report, I have:
new SimpleDateFormat("HH:mm", $P{REPORT_LOCALE}).format($F{start_date});
However, for example, for "2015-03-02 11:45:00+01" I don't get 12:45 shown, I get 11:45.
Also, I need to sum-up the hours (they're intervals) and this gives me a 1hr (in this case) error.
Can anyone help me show the correct hour?
Thanks!
SimpleDateFormat takes a Date, not a Calendar - which means it can't be provided the time zone in the value itself.
Assuming you need to stick with SimpleDateFormat (rather than using Joda Time or Java 8's java.time, for example) then you'll need to set the time zone on the SimpleDateFormat itself. If you need to take the time zone from the data (rather than having a report-wide zone) then you'll need to call setTimeZone before formatting each value - but of course, you'll also need to make sure you've got the time zone in the value, and java.sql.Timestamp doesn't have any notion of a time zone, as far as I'm aware.

Dates from HSQL Database returns negative values in fastTime field

im extracting dates from my HSQL database and they display correctly but internally they seem to be wrong. Most of the Dates are defaults with 1970-01-01 as its value. While debugging i can see a field called "fastTime" which says it is -3.600.000 which is exactly one minute before it should be...
When i now mix these dates up with some generated values where fastTime is 0 the comparison is wrong and the wrong date is picked.
This is extremly annoying because just adding the value when extractng it from DB works for now but switching to another DBMS would require to revert this changes.
So.. Is this just a bug or whats going on?
If the dates display correctly, then they are correct for your time zone.
If the fastTime indicates the value you are reporting, it means your time zone is GMT+1hour. If the fastTime was 0, then the date would represent midnight at GMT, rather than in your time zone.
Your need to account for time zone when you peform comparisons in Java between dates that belong to different zones. You can use a Java Calendar object for this purpose.

Categories