I am developing a hospital management system for an assignment.I want to view patient details and display "not discharged" if the column date_of_discharge is null.I'm using mysql as database.Do I want to convert sql date to java util date before checking it null?
NULL is nothing
Do I want to convert … before checking it null?
No.
As others commented, NULL means “nothing at all”. A NULL is the same across all data types. So no need to convert, cast, or parse when simply asking if the value is NULL or not.
Instead of checking not null,can I directly check whether it is null
Yes. Use IS NULL or IS NOT NULL.
SELECT * FROM patient WHERE date_of_discharge IS NULL ;
…or…
SELECT * FROM patient WHERE date_of_discharge IS NOT NULL ;
Avoid NULLs
display "not discharged" if the column date_of_discharge is null.
Following Dr. Chris Date’s advice, I avoid using NULL wherever possible, as if it were the work of the devil (which it may be!).
Instead, assign a certain value of your own arbitrary choosing to signify no-value-yet-assigned. Perhaps the epoch reference date of Unix time and other systems: the first moment of 1970 in UTC, 1970-01-01T00:00Z.
In Java, we have available as pre-defined constants: LocalDate.EPOCH and Instant.EPOCH.
Never cast between java.util.Date & java.sql.Date
convert sql date to java util date before checking it null
No, never cast between these types. You should ignore the fact that java.sql.Date inherits from java.util.Date. By inheriting, the java.sql.Date actually carries a time-of-day. Yet java.sql.Date portrays itself as representing a date-only value without time-of-day and without time zone — but this is only a pretense. As a workaround, to fulfill that pretense, that time-of-day is set to midnight of some time zone. But the java.util.Date always represents a moment in UTC. So by casting, you will inadvertently be mixing in the effect of some time zone.
Confusing? Yes. This is a terribly bad design, an awful hack, and is one of many reasons to avoid these old legacy date-time classes. Use java.time classes instead.
JDBC 4.2
As of JDBC 4.2 we can directly exchange java.time objects with the database. Use PreparedStatement::setObject and ResultSet::getObject methods.
The java.sql.Date class that pretends to hold a date-only value is supplanted by the java.time.LocalDate. The LocalDate class actually does hold only a date, without a time-of-day and without a time zone.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
…and…
myPreparedStatement.setObject( … , localDate ) ;
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.
Related
I have for example 30 users and for everyone i want to set vacation with random start_day and random end_day of vacation. I want to use Date, not LocalDate. If i must do with LocalDate this is the answer.
LocalDate date = LocalDate.now();
List<VacationUser> collectVacationUser = allVacationUsers.stream()
.map(user -> {
if (inVacation()) {
return new VacationUser(date.minusDays(ThreadLocalRandom.current().nextInt(1, 5)),
date.plusDays(ThreadLocalRandom.current().nextInt(1, 5)));
} else {
return new VacationUser(user.getPrimaryEmail());
}
}).collect(toList());
return collectVacationUser;
}
I want to do this with Date, because in JSON date format with 'Date' is this "yyyy/mm/dd", in the other hand if I use LocalDate a format in JSON is something like this
"year":2018,"month":"AUGUST","era":"CE","dayOfMonth":16,"dayOfWeek":"THURSDAY","dayOfYear":228,"leapYear":false,"monthValue":8,"chronology":{"id":"ISO","calendarType":"iso8601"
tl;dr
Use types appropriate to your values: LocalDate
Never use the terrible legacy class java.util.Date
Learn to use converters/adapters in your Java⇔JSON serialization framework
Use standard ISO 8601 formats for date-time values whenever possible
Details
Use appropriate types to represent your data values. For a date-only value, without a time-of-day and without a time zone, the appropriate type is LocalDate.
Never use java.util.Date. That terrible class was supplanted years ago by the java.time classes.
As for generating textual representations in JSON, that is an entirely separate issue.
JSON has very few data types and none of them are date-time related. So whatever JSON output you are getting for your LocalDate input is a function of your particular Java-to-JSON library you are using. You do not divulge what library, so we cannot provide further assistance.
I can tell you that there is an established practical international standard for representing date-time values: ISO 8601. I strongly suggest always using these standard formats when serializing your date-time values to text.
For a date-only value, the standard format is YYYY-MM-DD such as 2018-01-23.
The java.time classes use these standard formats by default when parsing/generating strings.
LocalDate.parse( "2018-01-23" ) ;
And:
myLocalDate.toString()
2018-01-23
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
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.
I have this piece of code
while(activecheck.next()){
Date status;
String vincheck;
Date curr = new Date();
int datecheck;
status = activecheck.getDate(8);
vincheck = activecheck.getString(2);
String update = "UPDATE Auctions SET status = '"+inactive+"' WHERE vin = '"+vincheck+"'";
datecheck = status.compareTo(curr);
if(datecheck < 0){
stmt6.executeUpdate(update);
}
}
Which iterates through a mysql table checking for inactive bids. I am trying to check whether the date and time listed in the sql row has been passed by the current time. However, whenever I do this, it seems to only be comparing the dates, and not the times. What could be the cause of this?
This is the format I am using : yyyy-MM-dd HH:mm:ss`
You should use type which is called Timestamp instead of the date. This way you will cover the date and the current time
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
tl;dr
if(
myResultSet.getObject( … , Instant.class ) // Retrieve `Instant` (a moment in UTC) from database using JDBC 4.2 or later.
.isBefore( Instant.now() ) // Comparing to the current moment captured in UTC.
)
{
…
}
java.util.Date versus java.sql.Date
You may be confusing this pair of unfortunately mis-named classes. The first is a date-with-time type, in UTC. The second is a date-only type. Actually the second pretends to be a date-only type but actually has a time-of-day set to 00:00:00. Even worse, the second inherits from the first, but the documentation instructs us to ignore that fact.
Confusing? Yes. These awful classes are very poorly designed. Avoid them.
java.time
You are using terribly troublesome old date-time classes that were supplanted years ago by the java.time classes.
Instant
The java.util.Date class is replaced by java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
LocalDate
The java.sql.Date class is replaced by java.time.LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
JDBC 4.2
As of JDBC 4.2 and later, you can directly exchange java.time classes with your database. No need to ever use java.sql or java.util date-time types again.
Tip: Make a habit of always using a PreparedStatement to avoid SQL Injection risk. Not really any more work once you get used to it.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Smart objects, not dumb strings
This is the format I am using : yyyy-MM-dd HH:mm:ss`
Date-time values stored in a database do not have a “format”. Those values are stored by some internally-defined mechanism that does not concern us. They are not strings (not in any serious database, that is).
Your database, and your Java date-time objects, can parse a string representing a date-time value to create that value. And they can generate a string to represent that value. But the string and the date-time value are distinct and separate, and should not be conflated.
Use java.time objects to exchange date-time values with your database, not mere strings, just as you would for numbers and other data types your database comprehends. Use strings only for communicating textual values.
Compare
To compare your retrieved values against the current moment, use the isBefore, isAfter, and equals methods of Instant class.
Instant now = Instant.now() ;
…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
boolean isPast = instant.isBefore( now ) ;
if ( isPast ) {
…
}
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, 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.
I am trying to get current time in other time zone. I used this code for this:
GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println(calender.getTime());
But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?
Ahh, the joys of the Java Date/Time API ...
What you want (aside from a better API, such as Joda Time) is a DateFormat. It can print dates in a time zone you specify. You don't need Calendar for that.
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());
Calendar is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.
When you are done with these calculations, then you can get the result by calling calendar.getTime() which returns a Date.
A Date is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString on a Date it will just print something in your default timezone. For more control, use DateFormat.
What you are doing right now is:
Getting a calendar in Bangkok time zone
get the Date object for this time( which is in ms since some date January 1, 1970, 00:00:00 GMT)
print out this Date in your timezone (Date.toString())
You should use a Formatter class to get the result you want. e.g. SimpleDateFormat
An alternative solution would be to use a less confusing Date/Time library. e.g. JodaTime or the new java.time package of Java8
tl;dr
ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )
java.time
The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.
Use only the modern java.time classes defined in JSR 310.
ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.
See this code run live at IdeOne.com.
2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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.
Should I use java.util.Date or java.sql.Date?
I have a VisualFox database and I have retrieved the entities with the IntelliJ Idea wizard using an appropiate jdbc type 4 driver.
The ide (or the driver) has created the date fields as Timestamp. However, the date fields are not timestamps but Date fields, they store year, month and day only.
So I wonder if I should switch to java.util.Date or java.sql.Date. At first glance I thought that java.sql.Date should be the appropiate one, but it has many methods declared as deprecated.
tl;dr
Should I use java.util.Date or java.sql.Date?
Neither.
Both are obsolete as of JDBC 4.2 and later. Use java.time classes instead.
date-only valueFor a database type akin to SQL-standard DATE, use java.time.LocalDate.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
myPreparedStatement.setObject( ld , … ) ;
date with time-of-day in UTC valueFor a database type akin to SQL-standard TIMESTAMP WITH TIME ZONE, use java.time.Instant.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
myPreparedStatement.setObject( instant , … ) ;
Details
The question and other answers seem to be over-thinking the issue. A java.sql.Date is merely a java.util.Date with its time set to 00:00:00.
From the java.sql.Date doc (italicized text is mine)…
Class Date
java.lang.Object
java.util.Date ← Inherits from j.u.Date
java.sql.Date
…
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. ← Time-of-day set to Zero, midnight GMT/UTC
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
Date-Only versus Date-Time
The core problem is:
SQLIn SQL, the DATE data type stores a date-only, without a time-of-day.
JAVAIn the badly designed date-time library bundled with the early versions of Java, they failed to include a class to represent a date-only.
Instead of creating a date-only class, the Java team made a terrible hack. They took their date-time class (the misnamed java.util.Date class, containing both date and time) and extended it to have an instance set its time-of-day to midnight UTC, 00:00:00. That hack, that subclass of j.u.Date, is java.sql.Date.
All this hacking, poor design, and misnaming has made a confusing mess.
Which To Use
So when to use which? Simple, after cutting through the confusion.
When reading or writing to a database’s date-only column, use java.sql.Date as it clumsily tries to mask its time-of-day.
Everywhere else in Java, where you need a time-of-day along with your date, use java.util.Date.
When you have a java.sql.Date in hand but need a java.util.Date, simply pass the java.sql.Date. As a subclass, a java.sql.Date is a java.util.Date.
Even Better
In modern Java, you now have a choice of decent date-time libraries to supplant the old and notoriously troublesome java.util.Date, Calendar, SimpleTextFormat, and java.sql.Date classes bundled with Java. The main choices are:
Joda-Time
java.time(inspired by Joda-Time, defined by JSR 310, bundled with Java 8, extended by the ThreeTen-Extra project)
Both offer a LocalDate class to represent a date only, with no time-of-day and no time zone.
A JDBC driver updated to JDBC 4.2 or later can be used to directly exchange java.time objects with the database. Then we can completely abandon the ugly mess that is the date-time classes in the java.util.* and java.sql.* packages.
setObject | getObject
This article published by Oracle explains that the JDBC in Java 8 has been updated transparently to map a SQL DATE value to the new java.time.LocalDate type if you call getObject and setObject methods.
In obtuse language, the bottom of the JDBC 4.2 update spec confirms that article, with new mappings added to the getObject and setObject methods.
myPreparedStatement.setObject( … , myLocalDate ) ;
…and…
LocalDate myLocalDate = myResultSet.getObject( … , LocalDate.class ) ;
Convert
The spec also says new methods have been added to the java.sql.Date class to convert back and forth to java.time.LocalDate.
public java.time.instant toInstant()
public java.time.LocalDate toLocalDate()
public static java.sql.Date valueOf(java.time.LocalDate)
Time Zone
The old java.util.Date, java.sql.Date, and java.sql.Timestamp are always in UTC. The first two (at least) have a time zone buried deep in their source code but is used only under-the-surface such as the equals method, and has no getter/setter.
More confusingly, their toString methods apply the JVM’s current default time zone. So to the naïve programmer it seems like they have a time zone but they do not.
Both the buried time zone and the toString behavior are two of many reasons to avoid these troublesome old legacy classes.
Write your business logic using java.time (Java 8 and later). Where java.time lacks, use Joda-Time. Both java.time and Joda-Time have convenient methods for going back and forth with the old classes where need be.
Replacements:
java.util.Date is replaced by java.time.Instant
java.sql.Timestamp is replaced by java.time.Instant
java.sql.Date is replaced by java.time.LocalDate.
java.sql.Time is replaced by java.time.LocalTime.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
All three java.time.Local… classes are all lacking any concept of time zone or offset-from-UTC.
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, 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.
Well, according to this article you can use javax.sql.Date without #Temporal annotation which can save some coding from you. However java.util.Date is easier to use across your whole application.
So I would use
#Column(name = "date")
#Temporal(TemporalType.DATE)
private java.util.Date date;
In general, I find it advisable to use the java.util.Date, since you can use it anywhere in your program without either converting the type or polluting your application with SQL-specific code.
I am not aware of a scenario where 'java.sql.Date' would be a better fit.
According to Java doc, it is suggested to use appropriate Date type as per underlying database.
However, with Java 8, a rich set of classes under java.time package have been provided and it must be used if application is written with Java 8.
The class javaxjava.sql.Date extends java.util.Date with minor changes for miliseconds container so that it can support the Database DATE type effectively. This, we can save the #Temporal annotation typing from entity class.
However, java.util.Date could be used for better scalability in entire application so that it can be easily used to store time along with date.
I know how to retrieve timestamp with milliseconds:
to_char(systimestamp ,'YYYY-MM-DD HH24:MI:SS,FF9')
Can anyone please advise, is the timestamp data type sufficient to store the date with milliseconds or can I use varchar2? I am trying to insert this value from Java.
Yes, TIMESTAMP allows precision down to nanoseconds if you want it.
If you only need milliseconds, you just want a TIMESTAMP(3) column.
Use a java.sql.Timestamp (which again goes down to nanoseconds, if you need it to) on the Java side. Note that you should avoid doing your to_char conversion if possible - perform any string conversions you need client-side; fetch data as a timestamp, and send it as a timestamp.
tl;dr
Use smart objects, not dumb strings. Use java.time for nanosecond resolution.
myResultSet.getObject( … , LocalDateTime.class )
java.time
The Answer by Jon Skeet is correct, but now outdated. The java.sql.Timestamp class is supplanted by the java.time classes such as Instant and LocalDateTime.
The java.time classes have a resolution of nanoseconds, more than enough for your milliseconds.
Oracle database seems to have a TIMESTAMP type that is equivalent to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. That means it lacks any concept of time zone or offset-from-UTC. For such a column, use LocalDateTime in Java as it too lacks any concept of zone/offset.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
For storing into a field of type similar to SQL-standard TIMESTAMP WITH TIME ZONE where do have respect for zone/offset, use Instant:
Instant instant = Instant.now() ; // Capture current moment as fine as nanoseconds. In practice, we get microseconds in Java 9, but only milliseconds in Java 8.
As of JDBC 4.2 and later, we can directly exchange java.time objects with the database via PreparedStatement.setObject and ResultSet.getObject. So use these smart objects rather than mere strings to communicate date-time values.
The java.time classes generate strings in standard ISO 8601 formats. Just call toString.
String output = instant.toString() ;
String output = ldt.toString() ;
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.