Inserting the exact time into a database - java

When you insert the following into a SQL database:
Date now = new Date(System.currentTimeMillis());
PreparedStatement audit = sqlConn.prepareStatement("INSERT INTO [Table](Date) VALUES (?)");
audit.setDate(1, now);
audit.execute();
This is the result:
2013-09-06 00:00:00.000
How do I also get the time information inserted into the database?
Edit: The column datatype is DateTime.

You may be confusing:
The java.util.Date class which represents a date and a time-of-day in UTC
The java.sql.Date class which represents a date-only, without time-of-day and without time zone.
Actually, java.sql.Date extends java.util.Date so it does in fact inherit a time-of-day but pretends to not have a time-of-day by setting it to 00:00:00.0 in UTC. The class doc tells you ignore the inheritance relationship (it's a hack). Confusing? Yes, these old date-time classes are a mess, poorly designed, confusing, and troublesome.
These old classes were supplanted by the java.time classes built into Java 8 and later. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
If your database column is of a type similar to the SQL standard type TIMESTAMP WITH TIME ZONE, then you can use either:
InstantA moment on the timeline in UTC with a resolution up to nanoseconds.Instant instant = Instant.now();
ZonedDateTimeLike an Instant but adjusted into a particular time zone.ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
If your JDBC driver complies with JDBC 4.2 spec, you can pass either of these via the setObject method on a PreparedStatement.
If your driver does not support the direct use of java.time types, fall back to using java.sql types. Find new methods added to the old classes for converting to/from java.time types. You are looking for the java.sql.Timestamp class in particular for a date-time value, which can convert to/from Instant. From a ZonedDateTime you can extract an Instant for this purpose of conversion.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );
Going the other direction.
Instant instant = mySqlTimestamp.toInstant();

Some database only store up to the second precision for the date.
SQLserver's datetime supports fractional seconds, but it rounds to the nearest 3 milliseconds.
If you need more precision, store your date as a bigint type and pass the now.getTime() Java long value instead.

Related

ISO 8601 datetime now

I need exactly that format in java which in C# is
DateTime.Now.ToString("o"). Sample returned date for DateTime.Now.ToString("o") is
2016-03-10T11:24:59.7862749+04:00
and then in sql it's inserted as
2016-03-10 11:24:59.786
I'm trying to insert same date format from java. I use that:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
and it returns this
2016-03-10T07:29+0000
Because of that format then it goes in error. How can I change format to be exactly which I want?
For Java 7 you can use:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
System.out.println(df.format(new Date()));
This uses the pattern symbol XXX which will print the colon inside the offset, too. However, for Java-6 this feature is not offered. And the precision is always constrained to milliseconds.
For Java-8, you can also use:
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println(OffsetDateTime.now().format(dtf)); // 2016-03-10T08:46:44.849+01:00
This enables nanosecond precision if such a clock is available (starting with Java-9).
For Java-6 either apply a hack based on SimpleDateFormat or use external libraries:
// Java-6 (SimpleDateFormat)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String text = sdf.format(new Date());
text = text.substring(0, text.length() - 2) + ":" + text.substring(text.length() - 2);
System.out.println(text);
// Joda-Time
DateTime now = DateTime.now();
System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").print(now));
// Time4J
Moment now = SystemClock.currentMoment();
System.out.println(Iso8601Format.EXTENDED_DATE_TIME_OFFSET.withStdTimezone().format(now));
The Answer by Meno Hochschild is correct. I'll just add some more comments and some SQL-specific code.
Avoid Old Date-Time Classes
The old date-time classes, java.util.Date/.Calendar & java.text.SimpleDateFormat, are poorly designed, confusing, and troublesome. Avoid them.
The old clases have been supplanted by the java.time framework built into Java 8 and later.
For use before Java 8, check out the ThreeTen-Backport project.
Nanoseconds
The java.time classes have nanosecond resolution. So you will not have the problem of data loss where 2016-03-10T11:24:59.7862749+04:00 gets truncated to 2016-03-10 11:24:59.786 because of millisecond resolution used by the old classes.
Getting the current moment in Java 8 is limited to milliseconds, three digits of decimal fraction of second, due to legacy issue. Java 9 will get the current moment in nanoseconds, up to nine digits of decimal fraction (provided your computer’s hardware clock can provide such fine resolution).
ISO 8601
The ISO 8601 standard defines sensible text formats for date-time values. For example, 2016-03-09T23:24:33Z or 2016-03-09T22:24:33-01:00. The java.time classes use these by default, so no need to define parsing patterns.
Instant
An Instant is a moment on the timeline in UTC.
Instant instant = Instant.now();
Call Instant::toString to generate a string in standard format.
String output = instant.toString();
2016-03-09T23:24:33.123Z
OffsetDateTime
Apply a ZoneOffset to get an OffsetDateTime.
ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes( -5 , 30 );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );
ZonedDateTime
If you know the full time zone rather than just the offset-from-UTC, apply a ZoneId to get a ZonedDateTime.
Use proper time zone names.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ); // "Europe/Paris", "America/Montreal", etc.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
java.sql.Timestamp
Hopefully the JDBC drivers will be updated to directly use the java.time types. Until then we convert to java.sql types for transferring data in/out of database.
As noted above, java.time can handle nanoseconds. So does java.sql.Timestamp. But your database may not. Some databases are limited to whole seconds, milliseconds, or microseconds. When data is passed via JDBC to the database, the database may truncate.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
…and going the other direction…
Instant instant = ts.toInstant();
Note that an Instant is always in UTC by definition. So no need to perform the kind of code attempted at the end of the Question.
Work Flow
You should minimize your use of strings when working with date-time. Maximize your use of helpful date-time classes/objects, namely java.time classes. Stop thinking of strings as date-time values -- they are a textual representation of a date-time value.
Do not insert/retrieve date-time values to/from your database as strings. Use the java.sql objects such as java.sql.Timestamp and java.sql.Date. Use PreparedStatement and the "set/get" methods such as setTimestamp/getTimestamp. And virtually always define your columns in database as TIMESTAMP WITH TIME ZONE rather than “without time zone”.
When getting data from database, use the java.sql types. But as soon as is possible, convert to java.time types. The java.sql types are a mess, a dirty hack, and should be used only for data transfer not business logic.
Generally best to use UTC in your business logic, data storage, data exchange, API calls, and so on. Adjust into a time zone only when expected by a user or required by a data sink.
use this format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Example:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(df.format(new Date()));

How to convert MST time zone to IST format and then want to persist that in database in java

I am new to Java. I have a web application that runs on a godaddy server in the USA.
The problem is when we use the application anywhere we need to update the date with the respective timestamp in database. While updating it is storing as MST format date instead of IST format (when I tried from India). Let me know how can I solve this.
Thanks in advance.
My code is as follows.
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
f.setTimeZone(TimeZone.getTimeZone("IST"));
String date = f.format(new Date());
Date aptDate = formatter.parse(date);
System.Out.Print("The IST time is : "+ date);
Here I am getting the string format date, I want to convert into a date object and then store in the database.
When I apply the conversion it is giving earlier date. Let me what is the wrong going.
Your Question is confusing. Here are some guidelines to re-orient your thinking.
You are using old date-time classes now outmoded by the java.time framework built into Java 8 and later. Avoid the old classes as they are poorly designed, confusing, and troublesome.
Stop using the 3-4 letter codes such as IST. Do you mean India Standard Time or Irish? These codes are neither standardized nor unique. Erase these codes from both your thinking and your code. Use proper time zone names in the format of continent/region.
Do most of your work, your business logic, data exchange, data storage, and database in UTC. Apply a time zone only when expected by your user or data sink.
Use date-time types when defining columns in your database. Do not store date-time values as strings.
Use the java.sql types to transfer date-time values in and out of the database. Convert immediately to java.time types. Eventually JDBC drivers will be updated to use java.time types directly. Until that day, use new methods added to the old java.sql classes for convenient conversions.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Convert to java.sql.Timestamp to write to the database.
java.sql.Timestamp ts = java.sql.Timestamp.from( now );
To the other direction, for retrieval, convert from java.sql to java.time.
Instant instant = myJavaSqlTimestamp.toInstant();
Notice that for database work we do not care about time zone as the values are all in UTC on all sides: Java, JDBC, SQL, database.
To view the wall-clock time for some locality, apply a time zone (ZoneId) to generate a ZonedDateTime object.
ZoneId zoneIdEdmonton = zoneId.of( "America/Edmonton" );
ZonedDateTime zdtEdmonton = ZonedDateTime.ofInstant( instant , zoneIdEdmonton );
You can apply yet another time zone. Note that java.time uses immutable objects. An new object arises from an old object rather than changing (“mutating”) the original. In this example, the zdtEdmonton object begets the zdtKolkata object.
ZoneId zoneIdKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtEdmonton.withZoneSameInstant( zoneIdKolkata );

convert a unix timestamp to a postgres equivalent timestamp in java

I have a field in postgres
Column | Type
created_at | timestamp without time zone
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
I want to convert it to timestamp in java so that I can store with activejdbc into postgres
I tried the following
Date convertedTime = new Date(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
But I get the following error:
Can't infer the SQL type to use for an instance of java.util.Date. Use setObject() with an explicit Types value to specify the type to use.
Should I be using a different way to convert the date first?
java.sql.Timestamp timestamp = new Timestamp(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
Instead of util you have tried with java.sql.Date.
Its a native type of SQL.
Incompatible types
I have a field in postgres …
timestamp without time zone …
…and…
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
This is a contradiction.
The SQL-standard type TIMESTAMP WITHOUT TIME ZONE purposely lacks any indicator of time zone or offset-from-UTC. As such, this type does not represent a moment, is not a point on the timeline. This type represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.
If you are trying to track specific moments, use the other SQL-standard type, TIMESTAMP WITH TIME ZONE. In Postgres, all values of this type are stored in UTC (an offset of zero). If you pass a value indicating some other offset or time zone, Postgres adjusts the value to UTC before storing.
When retrieving a value from a column of type TIMESTAMP WITH TIME ZONE in Postgres, you are always getting a value in UTC. Unfortunately, some well-intentioned tools or drivers sitting between you and the database may decide the dynamically apply a time zone to the value. While well-intentioned, I consider this quite the anti-feature. This behavior creates the illusion of a time zone stored in the database while in fact Postgres only stores UTC in this type.
Date convertedTime = new Date(createdAtTime*1000L);
The java.util.Date class is terrible, poorly designed and flawed. Never use this class nor its siblings, Calendar, SimpleDateFormat, and such. These are all legacy now, supplanted years ago by the modern java.time classes defined in JSR 310.
Instant
The Instant class takes over for java.util.Date. Both classes represent a moment in UTC, though Instant has a finer resolution of nanoseconds versus milliseconds.
unix timestamp stored in long in Java
If you have a count of whole seconds from the epoch reference of the first moment of 1970 in UTC, 1970-01-01T00:00:00Z, convert to an Instant.
Instant instant = Instant.ofEpochSecond( 1_539_555_140L ) ;
Tip: Do not make a habit of tracking time as a count-from-epoch. This is ambiguous (different systems use different resolutions and different epoch references), error-prone, and makes debugging/logging treacherous. Use java.time objects and standard ISO 8601 strings for representing date-time values.
Your JDBC driver may be able to accept an Instant.
myPreparedStatement.setObject( … , instant ) ;
Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
OffsetDateTime
If not supporting Instant, use convert to OffsetDateTime. Any JDBC 4.2 or later driver is required to support OffsetDateTime.
OffsetDateTime represents a date and time-of-day with an offset-from-UTC. In contrast, Instant is fixed at UTC, serving as a basic building-block class in java.time framework. Also, OffsetDateTime is more flexible with abilities such as generating strings in various formats versus Instant using only standard ISO 8601 format.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval:
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
…or…
Instant instant = myResultSet.getObject( … , OffsetDateTime.class ).toInstant() ;
LocalDateTime
If you are not trying to represent moments, such as database type TIMESTAMP WITHOUT TIME ZONE, use the LocalDateTime class.
But if you are thinking use of these types is somehow avoiding the work of using time zones in tracking moments, you are sorely mistaken. This is a “pay now or pay later” situation: Either learn basic date-time concepts and handling practice now, or desperately wrestle with a horrible mess of failed data later.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I see that your Database column stores value as time stamp without time zone,
why don't you try this
Timestamp current = Timestamp.from(Instant.now());
record.set("created_at", current);//I don't know if you might need to parse
record.saveIt();

Date.toString() - sql vs util dates

I need to remove time from a Date Object. Here is my try,
Code:
System.out.println("date " + dbDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("formatter.format(dbDate) " + formatter.format(dbDate));
System.out.println("final " + formatter.parse(formatter.format(dbDate)));
Output:
date 2011-12-03 23:59:59.0
formatter.format(dbDate) 2011-12-03
final Sat Dec 03 00:00:00 IST 2011
I want to the final date to display in 2011-12-03. But after conversion toString() of that Date is in different format. I am missing something. Please help.
Update:
In my application, I have two different methods to get dbDate. EXPIRY_DATE column is type of DATE.
First query uses dbDate = (java.util.Date) rs.getDate("EXPIRY_DATE");.
For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03
Second query uses dbDate = rs.getTimestamp("EXPIRY_DATE");
For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03 23:59:59.0.
This is my problem. As I thought toString() was giving problem, I didn't mention the full problem.
Solution:
I did not have choices to avoid java.sql.Date as my application methods have multiple usages.
I tried the below and worked,
dbDate = new java.sql.Date(dbDate.getTime());
I need to remove time from a Date Object
You can't. The java.util.Date object contains both the date and time. Its toString() is also in a fixed format. If you want to represent it without time to humans, then you need to convert it to a String like as you already did. Or, if you intend to store it in the DB without the time (as the db part in the variable name dbDate suggests), then you need to convert it to java.sql.Date.
preparedStatement.setDate(1, new java.sql.Date(dbDate.getTime()));
// ...
Update as per your update, the ResultSet#getDate() returns an instance of java.sql.Date, not java.util.Date (but it is a subclass of java.util.Date, that's why the unnecessary cast worked; please note that casting is not the same as converting, a real conversion would be new java.util.Date(dbDate.getTime())). As you can read in the javadoc of the toString() method of java.sql.Date, it's indeed in yyyy-MM-dd format.
So, your concrete problem is that you're confusing java.sql.Date with java.util.Date and that you're misgrasping the internal workings of java.util.Date and been mislead by the toString() method. Everything is working as intented.
Related:
Handling MySQL datetimes and timestamps in Java
If what you want to do is remove the time part of the Date object:
Use a Calendar to remove the time part of your Date object. As pointed out in this question: Java Date cut off time information.
If you only want to obtain a String representation without the time part of the Date object:
You've got to use SimpleDateFormat.format(). You can't make Date.toString() return a different value, it will always use that pattern. Look at its source code.
When you last call formatter.parse() you get back a Date object; the concatenation then makes an implicit call to Date.toString(): the format returned by this call is the default for the locale set in the JVM.
What you must understand is that the Date object has no knowledge of the string representation, internally it's just an aggregate of inte
I have encountered similar problem for those who encounters the same problem as mine I write this entry:
The problem is the date value that is taken from database and passed to the web client is in format yyyy-mm-dd but in the application for the first entry there is not database value so we create date object and passed the value to web client which gives us timestamp value. The value that will be passed to web client must be in date format so SimpleDateFormat is not a good choice for me
So from this post ı understand the difference of java.sql.date and java.util.date and then create first object as
Date date = new java.sql.Date(1430454600000L);
which gives yyyy-mm-dd value for toString method.
java.time
The Answer by BalusC is correct: You cannot eliminate a time-of-day from a class object defined to hold a date plus a time-of-day.
Also, you are using troublesome old classes (java.util.Date and java.sql.Date) that are now obsolete, supplanted by the java.time classes.
Instead, use a date-only class for a date-only value. The LocalDate class represents a date-only value without time-of-day and without time zone. The java.sql.Date pretends to do the same, but actually does carry a time of day due to very poor design decision of inheriting from java.util.Date. Avoid java.sql.Date, and use only java.time.LocalDate instead.
You are starting with a java.util.Date object apparently. That represents a point on the timeline in UTC with a resolution in milliseconds. So using that to determine a date requires a time zone. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
To get a date-only value from your java.util.Date, first convert to its java.time replacement, Instant. To convert back and forth, call new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
That value is in UTC by definition. Apply your desired time zone (ZoneId) to generate a ZonedDateTime.
ZonedDateTime zdt = instant.atZone( z ) ;
Finally, extract your desired LocalDate object from ZonedDateTime.
LocalDate ld = zdt.toLocalDate() ;
As of JDBC 4.2 and later, you can directly exchange java.time classes with your database. So no need to use the the java.sql classes such as java.sql.Date and java.sql.Timestamp.
myPreparedStatement.setObject( … , ld ) ;
Retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

datetime datatype in java

Which data type can I use in Java to hold the current date as well as time?. I want to store the datetime in a db as well as having a field in the java bean to hold that.
is it java.util.Date ?
java.util.Date represents an instant in time, with no reference to a particular time zone or calendar system. It does hold both date and time though - it's basically a number of milliseconds since the Unix epoch.
Alternatively you can use java.util.Calendar which does know about both of those things.
Personally I would strongly recommend you use Joda Time which is a much richer date/time API. It allows you to express your data much more clearly, with types for "just dates", "just local times", "local date/time", "instant", "date/time with time zone" etc. Most of the types are also immutable, which is a huge benefit in terms of code clarity.
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
java.time
The java.time framework built into Java 8 and later supplants both the old date-time classes bundled with the earliest versions of Java and the Joda-Time library. The java.time classes have been back-ported to Java 6 & 7 and to Android.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Apply an offset-from-UTC (a number of hours and possible minutes and seconds) to get an OffsetDateTime.
ZoneOffset offset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );
Better yet is applying a full time zone which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Database
Hopefully the JDBC drivers will be updated to work directly with the
java.time classes. Until then we must use the java.sql classes to move date-time values to/from the database. But limit your use of the java.sql classes to the chore of database transit. Do not use them for business logic. As part of the old date-time classes they are poorly designed, confusing, and troublesome.
Use new methods added to the old classes to convert to/from java.time. Look for to… and valueOf methods.
Use the java.sql.Timestamp class for date-time values.
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( instant );
And going the other direction…
Instant instant = ts.toInstant();
For date-time data you virtually always want the TIMESTAMP WITH TIME ZONE data type rather than WITHOUT when designing your table columns in your database.
+1 the recommendation for Joda-time. If you plan on doing anything more than a simple Hello World example, I suggest reading this:
Daylight saving time and time zone best practices
Depends on the RDBMS or even the JDBC driver.
Most of the times you can use java.sql.Timestamp most of the times along with a prepared statement:
pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );
I used this import:
import java.util.Date;
And declared my variable like this:
Date studentEnrollementDate;
Since Java 8, it seems like the java.time standard library is the way to go. From Joda time web page:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Back to your question. Were you to use Java 8, I think you want LocalDateTime. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.
You can use Calendar.
Calendar rightNow = Calendar.getInstance();
Calendar
Date4j alternative to Date, Calendar, and related Java classes

Categories