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

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.

Related

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.

Converting datetime in millisec with timezone info

I have one simple question. How to achieve this format of date 1438117140000+0300. First part 1438117140000 its the time in millisec , that i convert with no problem, second part with timezone info is my headache , how to get it ??
You can use String.format for this purpose:
Date now = new Date();
System.out.println(String.format("%tQ%tz", now, now));
Executing the code just printed out this:
1438635740416+0300
The conversions for date/time are specified in the documentation. Here, I've used the following two conversion characters:
'Q': Milliseconds since the beginning of the epoch starting at 1
January 1970 00:00:00 UTC, i.e. Long.MIN_VALUE to Long.MAX_VALUE.
'z': RFC 822 style numeric time zone offset from GMT, e.g. -0800. This
value will be adjusted as necessary for Daylight Saving Time. For
long, Long, and Date the time zone used is the default time zone for
this instance of the Java virtual machine.
It looks like +0300 means +3 hours from GMT. so convert 0300 (3 hours) to milliseconds and add to 1438117140000. then convert to a date time as you are already
Split the value you have to '+' then add 3 hours as miliseconds to the first value of the array that split method returned.

From jFreeChart Millisecond to java.util.Date

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.

how can i get a date object that has only time

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.

Require help for SWT DateTime in Java

I retrieve a Date from the database using the ResultSet rsExpid.
Date joindate = rsExpid.getDate("join_date_ad");
System.out.println(joindate);
int year = joindate.getYear();
System.out.println(year);
int month =joindate.getMonth();
System.out.println(month);
int day = joindate.getDay();
System.out.println(day);
dateTimeJoin4.setDate(year, month, day);
When I print joindate to the console it shows correctly as 2011-08-03, but when I print the year to the console I was amazed to see 111. Similarly printing the month produced 7 and the day resulted in 3.
The variable dateTimeJoin4 is my SWT DateTime. It is not setting any value and it is also not giving any error message. Could please anybody help me on this?
Chances are you haven't read the documentation for Date.getYear and Date.getMonth:
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
and
Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.
respectively. Likewise Date.getDay returns the day of the week, not the day of the month - you want Date.getDate() for that (or preferrably a different API entirely, either Calendar or Joda Time).
This has nothing to do with SWT's DateTime type - after all, you only use that in the last line. When something behaves unusually, your first port of call should be the documentation. SWT's DateTime.setDate method is documented to require a year between 1752 and 9999, so 111 will be confusing it. Admittedly it would have been nice if it had thrown an exception, but even so...
The fact that you're calling deprecated methods should have been a hint to you, although Calendar also uses 0-11 for its months.
Personally I would strongly encourage you to use Joda Time for as much of your date and time work as you can. It's a far superior date and time API to the one built into Java. It's not immediately clear whether it's worth you using it here (if this is all you have to do) but if you're doing anything at all significant (including parsing, formatting or any kind of arithmetic) you should be using it.
I tried using this method and it worked correctly so this method can be useful to other.
Calendar startCal = Calendar.getInstance();
startCal.setTime(joindate);
int months= startCal.get(Calendar.MONTH);
int years= startCal.get(Calendar.YEAR);
int days= startCal.get(Calendar.DAY_OF_MONTH);
System.out.println(months+1);
System.out.println(years);
System.out.println(days);
dateTimeJoin4.setDate(years, months+1, days);
getDay() return the position of the day not the date like suppose today is Monday it will return 1, it start from the sunday with 0 value.
as well as the getMonth() return the position as starting value is 0 for january at now you getting the 7 instead of 8.
for getting date you can use the SimpleDateFormat or DateFormat by passing the format string in that you can get it
example links
http://www.roseindia.net/java/javadate/date-format.shtml
http://www.java-examples.com/java-simpledateformat-class-example

Categories