Is it possible in easy way to convert JRuby Time/DataTime/Data into java.util.Calendar including the timezone?
On #jruby I was given such code cal.set_time_in_millis(time.to_i) but I lost information about timezone in betwean. So the more specific question is how to convert the timezone but I prefered to ask more broad questin in case there is simpler way.
You can use the #to_java method to convert a Ruby time object to a java.util.Date:
require 'java'
Time.now.to_java
Note this coersion happens automatically when passing Ruby objects to Java methods.
I get known that the Time does not store timezone so what is returned by Time.now.zone is local timezone.
Therefore it is simple to convert to java.util.Data:
data = java.util.Date.new(date.to_i*1000)
Related
In retrieving a timestamp from Postgres or Oracle -- let's call it startDate -- is it better to use the resultSet.getString("startDate") call or resultSet.getTimestamp("startDate")?
Currently I'm using resultSet.getString("startDate") and it works fine, but it occurred to me it might be better practice to use getTimestamp().
Is there an established best practice? Could there be any unexpected consequences from using ResultSet.getString() on a timestamp?
Is it better to use ResultSet.getString() or ResultSet.getTimestamp()
to get a timestamp?
Neither.
It’s better to get a date-time object than a string since this better represents what the thing is and means, and should lend itself better to further operations in the Java program.
At the same time it’s far better to use the modern date-time classes from java.time than the old-fashioned Timestamp class. The latter has considerable design problems and has long been considered obsolete.
JDBC drivers are a little different, but see if you can get the correct time as either an Instant, an OffsetDateTime or if all else fails, then a LocalDateTime from your result set. In all cases use the two-argument getObject method. For example:
Instant instant = resultSet.getObject("startDate", Instant.class);
JDBC 4.2 specifies that java.time classes should be supported in this way. I believe all current SQL database engines have JDBC 4.2 compliant drivers out.
Only if you cannot use Java 8 or later, get a Timestamp as in your code. Next use the versions of the java.time classes from ThreeTen-Backport and use the DateTimeUtils class from ThreeTen-Backport for converting your Timestamp, best to en Instant, but if that happens to give you the wrong instant because of time zone trouble, then an LocalDateTime. Example:
Instant instant =
DateTimeUtils.toInstant(
resultSet.getTimestamp("startDate")
)
;
I would use resultSet.getTimestamp(). Then your data type is mapped properly from the code to the database. You can convert that result into a String if you wish then. I don't think there is a time cost of calling resultSet.getString(), but generally it's more appropriate to retrieve the correct data type.
I'm using ODA (which is wonderful) in my Java code but I'm having trouble with getting a date value from a field.
If I use:
DateTime lastApprDt = doc.getItemValue("LastApproved", Date.class);
then the parser objects and suggests "change type of lastApprDt to Date"
If I change the code to:
Date lastApprDt = doc.getItemValue("LastApproved", Date.class);
then the parser is happy but when I run the code I get an error:
[ODA::WARNING] Auto-boxing requested a com.ibm.security.util.calendar.BaseCalendar$Date but is returning a org.openntf.domino.impl.DateTime in item LastApproved for document id 992
I'm confused! If doc.getItemValue("LastApproved", Date.class) returns a Date type then why do I get the error?
Make sure that the lastApprDt Date is of type java.util.Date (and not of type com.ibm.security.util.calendar.BaseCalendar.Date).
The first is failing because it's trying to pass a Date object (the output from getItemValue()) into a DateTime object (lastApprDate).
I'm not quite sure why it's choosing to retrieve it as a com.ibm.security.util.calendar.BaseCalendar.Date, I can't see any reference to that class in the ODA code. It's worth checking the import statements in your code to make sure it's not chosen com.ibm.security.util.calendar.BaseCalendar.Date as the relevant Date class it thinks you want to use. I suspect it may have done. If so, change the import statement to use java.util.Date.
The code for autoboxing Dates looks for specific classes and how to convert them. java.util.Date is the most obvious one it's expecting. I recently added java.sql.Date, I believe for the last base 9.0.1 and first FP8 versions. java.util.Calendar is the other one supported. New Java 8 Date classes like LocalDateTime may seem good candidates because they have better timezone handling, but it's not easy to convert the DateTime timezone to a Java timezone and the timezone in a DateTime is readonly, so it wouldn't work for autoboxing back at the moment.
You shouldn't need to pass the full class name as the second parameter, I've got code running that just passes Date.class. That's what makes me suspect that the parser suggestion has guessed at the wrong class you wanted and imported com.ibm.security.util.calendar.BaseCalendar.Date.
If you are sure that the field contains a date value you should be able to get the java.util.Date with
Date lastApprDt = doc.getItemValue("LastApproved").get(0).toJavaDate();
I need to convert timestamps of the form yy-mm-dd-hh-mm-ss to a long that represents Unix time. Is there a class in Java's standard library that allows me to do this very easily? Or will I have to code the conversion algorithm myself?
I'm doing this on Android API level 7, in case that environment cuts off some of the necessary Java libraries.
You'll have to parse your timestamp (String.split() may prove useful here) to create a Calendar. From here you can call Calandar.getTimeInMillis() to get the UTC time.
I'm setting the standards for our application.
I've been wondering, what default date format should I choose to use ?
It should be:
Internationalization & timezone aware, the format should be able to represent user local time
Can be efficiently parsed by SimpleDataFormat (or alike, jdk classes only)
Programming Language agnostic (can parse in java, python, god forbid C++ :) and co.)
Preferably ISO based or other accepted standard
Easy to communicate over HTTP (Should such need arises, JSON or YAML or something in this nature)
Can represent time down to seconds resolution (the more precise the better, micro seconds if possible).
Human readable is a plus but not required
Compact is a plus but not required
Thank you,
Maxim.
yyyy-MM-ddThh:mmZ (See ISO 8601) You can add seconds, etc
You can read it easily, it will not be a problem for SimpleDateFormat.
The most canonical and standard form is probably "Unix Time": The number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970.
If you set that as the default time-format you can easily parse it, store it in memory, write it to disk, easily communicate it over HTTP and so on. It is also definitely an accepted standard, and in a sense it is "time-zone aware", since it is well-defined regardless of time-zones.
(This is the format in which I always store all my time stamps; in databases, in memory, on disk, ...)
The "right" default format really depends on what you're doing with it. The formats for parsing, storing, and displaying can all be different.
For storing the date you're (almost) always going to want to use UTC as aioobe says, even when you want to display it in user local time. I say "(almost)" but I really can't think of a case where I would not want UTC for a saved date. You may want to store the TZ information for where the date originated also, so you can report it in that local time, but more often you want to display the local time for the whoever is currently looking at the date. That means having a way to determine the current user's local time regardless of what the original local time was.
For displaying it, the "default format" should usually be determined by the viewers locale. 08/09/10 usually means 2010-Aug-9 in the U.S. ("Middle endian") but normally means 2010-Sep-8 in most of the rest of the world ("Little endian"). The ISO-8601 format "2010-09-10" is safe and unambiguous but often not what people expect to see. You can also look over RFC-3339 for Date and Time on the internet and RFC-2822 for message format (transmitting the date)
For parsing a date, you'll want to parse it and convert it to UTC, but you should be fairly flexible on what you accept. Again, the end users Locale and timezone, if discoverable, can help you determine what format(s) of string to accept as input. This is assuming user-typed strings. If you're generating a date/time stamp you can control the form and parsing will be no problem.
I also second BalusC link which I hadn't seen before and have now favorited.
I need to convert from the Unix TZ environment variable of the form:
stdoffset[dst[offset][,start[/time],end[/time]]]
into a Java TimeZone object.
For example, convert AEST-10AEDT-11,M10.1.0/02:00:00,M4.1.0/03:00:00 into a Java TimeZone object that represents "Australia\Sydney". Before I go and write the code myself I'd like to know I'm not inventing the wheel again, so does anyone know if there's a library already available that can do this?
It will be really hard to write such a conversion program. On Unix, you can have customized daylight rules and Java provides no such facility. It's possible to search through tzfile trying to find a match but you have to convert the TZ rule into the format used by tzfile, an enormous task.
Why don't you use the same zone id used in Java? For example, you can set TZ as,
export TZ=Australia/Sydney
This is supported on most modern Unix systems (like Linux, Mac OS X). Search /etc/zoneinfo or /usr/share/zoneinfo. If you can find a file for your timezone, the ID will work.
I also started on a custom TimeZone to handle the old TZ format but I was able to convince the sysadmin to use the zone id so I didn't finish it. The difficult part is to implement the useDaylightTime() because the rules used in TZ is very complicated.