datetime datatype in java - 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

Related

incompatible types: java.util.Date cannot be converted to java.sql.Date jdbc preparedstatement [duplicate]

java.util.Date vs java.sql.Date: when to use which and why?
Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.
Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. Quick semantics of each of these three are the following:
java.sql.Date corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.
java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.
One of the most common bugs when using JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.
Finally: Which one to use?
Depends on the SQL type of the field, really. PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.
Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you're actually missing stuff.
I'm really saying that none of the Dates should be used at all.
What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.
LATE EDIT: Starting with Java 8 you should use neither java.util.Date nor java.sql.Date if you can at all avoid it, and instead prefer using the java.time package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:
java.sql.Date - when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.
java.util.Date - when using libraries that use it. Otherwise, as little as possible, for several reasons:
It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.
It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.
Now, because j.u.D doesn't do it's job very well, the ghastly Calendar classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.
There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).
If you feel it's overkill to introduce a new dependency like Joda, longs aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.
tl;dr
Use neither.
java.time.Instant replaces java.util.Date
java.time.LocalDate replaces java.sql.Date
Neither
java.util.Date vs java.sql.Date: when to use which and why?
Both of these classes are terrible, flawed in design and in implementation. Avoid like the Plague Coronavirus.
Instead use java.time classes, defined in in JSR 310. These classes are an industry-leading framework for working with date-time handling. These supplant entirely the bloody awful legacy classes such as Date, Calendar, SimpleDateFormat, and such.
java.util.Date
The first, java.util.Date is meant to represent a moment in UTC, meaning an offset from UTC of zero hours-minutes-seconds.
java.time.Instant
Now replaced by java.time.Instant.
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
java.time.OffsetDateTime
Instant is the basic building-block class of java.time. For more flexibility, use OffsetDateTime set to ZoneOffset.UTC for the same purpose: representing a moment in UTC.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
You can send this object to a database by using PreparedStatement::setObject with JDBC 4.2 or later.
myPreparedStatement.setObject( … , odt ) ;
Retrieve.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
java.sql.Date
The java.sql.Date class is also terrible and obsolete.
This class is meant to represent a date only, without a time-of-day and without a time zone. Unfortunately, in a terrible hack of a design, this class inherits from java.util.Date which represents a moment (a date with time-of-day in UTC). So this class is merely pretending to be date-only, while actually carrying a time-of-day and implicit offset of UTC. This causes so much confusion. Never use this class.
java.time.LocalDate
Instead, use java.time.LocalDate to track just a date (year, month, day-of-month) without any time-of-day nor any time zone or offset.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).
Send to the database.
myPreparedStatement.setObject( … , ld ) ;
Retrieve.
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.
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 only time to use java.sql.Date is in a PreparedStatement.setDate. Otherwise, use java.util.Date. It's telling that ResultSet.getDate returns a java.sql.Date but it can be assigned directly to a java.util.Date.
I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:
preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
The java.util.Date class in Java represents a particular moment in time (e,.g., 2013 Nov 25 16:30:45 down to milliseconds), but the DATE data type in the DB represents a date only (e.g., 2013 Nov 25). To prevent you from providing a java.util.Date object to the DB by mistake, Java doesn’t allow you to set a SQL parameter to java.util.Date directly:
PreparedStatement st = ...
java.util.Date d = ...
st.setDate(1, d); //will not work
But it still allows you to do that by force/intention (then hours and minutes will be ignored by the DB driver). This is done with the java.sql.Date class:
PreparedStatement st = ...
java.util.Date d = ...
st.setDate(1, new java.sql.Date(d.getTime())); //will work
A java.sql.Date object can store a moment in time (so that it’s easy to construct from a java.util.Date) but will throw an exception if you try to ask it for the hours (to enforce its concept of being a date only). The DB driver is expected to recognize this class and just use 0 for the hours. Try this:
public static void main(String[] args) {
java.util.Date d1 = new java.util.Date(12345);//ms since 1970 Jan 1 midnight
java.sql.Date d2 = new java.sql.Date(12345);
System.out.println(d1.getHours());
System.out.println(d2.getHours());
}
java.util.Date represents a specific instant in time with millisecond precision. It represents both date and time information without timezone. The java.util.Date class implements Serializable, Cloneable and Comparable interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
java.sql.Date extends java.util.Date class which represents date without time information and it should be used only when dealing with databases. 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.
It inherits all public methods of java.util.Date such as getHours(), getMinutes(), getSeconds(), setHours(), setMinutes(), setSeconds(). As java.sql.Date does not store the time information, it override all the time operations from java.util.Dateand all of these methods throw java.lang.IllegalArgumentException if invoked as evident from their implementation details.

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()));

Java Date problems with TIMEZONE

I am struggling on this for days.
I have a date field, that gives a date on 'yyyy-MM-dd' format.
My Object have this field like this
#Temporal(TemporalType.DATE)
private Date finishdate;
I am on UTC, and this need to work all over the world, so on UTC-7 or UTC+7
On DataBase this value need to be store with 0 hours.
When the finishdate is filled, the format give me the timezone, so, for example:
I want 2014-10-01, with ZERO HOURS AND MINUTES AND SECONDS, on diferent timezones I catch:
2014-10-01 07:00:00:000
or
2014-09-01 17:00:00:000
The problem seams to be because of the Date liybrary, and i've found a solution with JODA Library, but i was told not to used it, and I need to find another solution.
So, need to convert to UTC Date, all dates,or other thing, but the day must be the same, like 1 October.
Anyone pass through this?
The Joda-Time library fixes issues like this, and I believe that is also the basis of the java.time package in Java 8, but for older Java versions this kind of problem occurs constantly.
The only consistent way I have seen for dealing with this without Joda time is to treat pure dates as a String ("2014-10-01") or Integer type (20141001) instead of a Date. and only convert to dates when needed in calculations. It is a real pain though.
Don't forget that SimpleDateFormat is not thread-safe. The answer saga56 gives may work but you'll have some very weird dates if there's any simultaneous use of the deserialiser. You need to 'new' the SimpleDateFormats each time, or (less favourably) do something else to ensure SimpleDateFormat is strictly limited to 1 thread at a time.
Solution to this issue.
We made an Custom Deserializer to every object of the type Date.
On ObjectMapperFactory, where we serialize or deserialize, i mapped to another class like this:
module.addDeserializer(Date.class, new DateDeserializerByDefault());
Then, on this class we did:
private static SimpleDateFormat dateFormatWithoutTimezome = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat dateFormatWithTimezone= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private static Pattern pattern = Pattern.compile("([0-9]{4})-([0-9]{2})-([0-9]{2})");
#Override
public Date deserialize(JsonParser jparser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String content = jparser.getValueAsString();
DateFormat format=(pattern.matcher(content).matches()) ? dateFormatWithoutTimezome : dateFormatWithTimezone;
try {
return format.parse(content);
} catch (ParseException e) {
throw new JsonParseException("Date parse failed", jparser.getCurrentLocation(),e);
}
}
And with this, when we receive Dates on diferent format, or with timezone to be stor we can change it to what we want.
I Hope this solution can help, I was stuck on this for 3,5 days. Dates are a pain in the a**.
The other Answers are correct but outdated.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
A LocalDate represents a date-only value without time-of-day and without time zone.
Your input string is in standard ISO 8601 format, so it can be parsed directly by LocalDate. No need to specify a formatting pattern.
String input = "2014-10-01";
LocalDate localDate = LocalDate.parse( input );
ZonedDateTime
You assume the day starts at time 00:00:00. But that is not always the case. In some time zones Daylight Saving Time (DST) or possibly other anomalies can mean the day starts at some other time on the clock such as 01:00:00. Let java.time determine the starting time of the first moment of a day. Specify a time zone, and assuming the tz database bundled with Java is up-to-date, then a call to LocalDate::atStartOfDay produces a ZonedDateTime for your date and first moment.
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
If you want the first moment of the day in UTC, specify the constant ZoneOffset.UTC (ZoneOffset being a subclass of ZoneId).
ZonedDateTime zdt = localDate.atStartOfDay( ZoneOffset.UTC );
Alternatively, use the more appropriate OffsetDateTime class. This is for values with a mere offset-from-UTC but lacking the set of rules for handling anomalies such as DST found in a full time zone. In UTC the day always starts at 00:00:00 which is stored in a constant LocalTime.MIN.
OffsetTime ot = OffsetTime.of( LocalTime.MIN , ZoneOffset.UTC );
OffsetDateTime odt = localDate.atTime( offsetTime );
Database
For database work, if you want a date-only value stored you should be using a data type along the lines of the SQL Standard type of DATE.
For a date-time value, nearly every serious database converts incoming data into UTC for storage in a TIMESTAMP WITH TIME ZONE type column. Your JDBC driver should help with this. But test and experiment as the behavior of drivers and databases varies tremendously.
With JDBC 4.2 and later, you may be able to pass/fetch the java.time types directly via setObject/getObject. If not, convert to java.sql types via new methods added to the old classes.

Java data type to hold only date

Which data type in Java can hold just the date and doesn't require a time component? For example, just to store 12/07/2012. I'm working with persisting the data to/from a database that has a date-only data type, so I'm looking for the best equivalent data type in Java.
from the JDK: 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.
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.
or from JodaTime: DateMidnight or LocalDate (thanks
#cdeszaq)
DateMidnight defines a date where the time component is fixed at
midnight. The class uses a time zone, thus midnight is local unless a
UTC time zone is used.
It is important to emphasise that this class represents the time of
midnight on any given day. Note that midnight is defined as 00:00,
which is at the very start of a day.
The other answers are out-dated.
The old date-time classes are notoriously troublesome and should be avoided.
java.time
The java.time framework is built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality is back-ported to Jave 6 & 7 and further adapted to Android.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDate = LocalDate.of( 2012 , 12 , 7 );
Textual representation
The toString method generates a String using standard ISO 8601 format.
localDate.toString() → 2012-12-07
For other formats use DateTimeFormatter.
SQL
JDBC drivers compliant with JDBC 4.2 can use the getObject and setObject methods to directly fetch/pass the java.time types such as LocalDate to SQL type DATE.
If your driver cannot do so, fall back to using the java.sql types. New methods have been added to the old classes to facilitate conversion.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
And the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Search Stack Overflow
Search Stack Overflow for many more discussions and examples of using java.time. For example, my answer to this similar Question.
Date class. It holds a UNIX timestamp. In most databases, you can specify a field to hold a timestamp as well. You can use DateFormat to format the timestamp however you want.
If you are using Java 8, you can use java.time.LocalDate.
Use Date class that is available.
It shows how hold only date(without time)
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date= new Date();
Date todayWithOutTime =formatter.parse(formatter.format(date));
Unfortunatelly, java.util.Date is something, that in SQL have name Timestamp. There's no pure type for Date only, javax.sql.Date extends java.util.Date and using this type for date manipulation in Java gives you no advantage.
I'm dealing with this using apache commons-lang class DateUtils:
Date myDate = DateUtils.truncate(timestamp, Calendar.DAY_OF_MONTH);
This will remove the time part and leave only date part.
Use Date class. This is the better way.

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.

Categories