how to mock timestamp and date function in java? - java

how to mock following code? i dont want to change my code.
Date date = new Date();
String res_timestamp=new Timestamp(date.getTime()).toString();
my code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
Date NOW = sdf.parse("2019-02-11 00:00:00");
Timestamp time=new Timestamp(NOW.getTime());
whenNew(Timestamp.class).withNoArguments().thenReturn(time);
how can i mock it? am finding hard to mock it.
how can i solve it?
note: i do not want to change my code. without changing my code i have to mock those two lines.

tl;dr
Use java.time.Clock, ZonedDateTime, Instant, ZoneId.
Inject an altered Clock object as a dependency: Clock.fixed( … ).
Never use Date, Calendar, SimpleDateFormat, Timestamp, TimeZone.
Pass an altered Clock object as a dependency
You are using terrible date-time classes that were supplanted years ago by the java.time classes defined by JSR 310.
The java.time.Clock class offers several alternate behaviors suitable for testing. These included a fixed point in time, altered cadences, and and adjustment from the current moment.
Pass one of these Clock objects to the various methods in the java.time classes for your testing purposes.
PST is not a time zone. Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-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/Los_Angeles" ) ;
Build up the specific moment you have in mind for your testing.
LocalDate ld = LocalDate.of( 2019 , 2 , 11 ) ;
LocalTime lt = LocalTime.MIN ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
zdt.toString(): 2019-02-11T00:00-08:00[America/Los_Angeles]
Calling Clock.fixed requires an Instant, a moment in UTC. We can adjust from our zoned value to UTC by extracting an Instant. Same moment, same point on the timeline, different wall-clock time.
Instant instant = zdt.toInstant() ;
instant.toString(): 2019-02-11T08:00:00Z
Specify a Clock that forever reports the current moment as that specific moment, without incrementing.
Clock clock = Clock.fixed( instant , z ) ;
clock.toString(): FixedClock[2019-02-11T08:00:00Z,America/Los_Angeles]
Inject the fixed clock as a dependency.
Instant now = Instant.now( clock ) ; // Tell me a lie.
now.toString(): 2019-02-11T08:00:00Z
See this code run live at IdeOne.com.
JDBC 4.2
If you were instantiating java.sql.Timestamp for use with a database, instead use the java.time classes. As of JDBC 4.2, we can exchange java.time objects with a database.
Your JDBC driver might have optional support for Instant.
myPreparedStatement.setObject( … , instant ) ; // Storing data.
Instant instant = myResultSet.get( … , Instant.class ) ; // Retrieving data.
Your driver must support OffsetDateTime.
myPreparedStatement.setObject( … , instant.atOffset( ZoneOffset.UTC ) ) ; // Storing data.
OffsetDateTime odt = myResultSet.get( … , OffsetDateTime.class ) ; // Retrieving data.
Adjust into a time zone.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
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

date is shown as fast milliseconds in java and not in proper format

I have the below declaration in java class
abc.setCreated(abcEntity.getCreatedDate());
and if I go deep inside the call inside abc entity
public Date getCreatedDate() {
return new Date(createdDate.getTime());
}
but the date in the outcome of
abc.setCreated(abcEntity.getCreatedDate());
shown as in request "created": 15704064000 and I want it to be shown as the date in DD-MM-YYYY format please advise how to achieve this
You can use SimpleDateFormat in java to get the date in that format. Instead of the time, pass the Date object like bellow.
ex:-
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = simpleDateFormat.format(new Date());
System.out.println(formattedDate);
tl;dr
Instant.
.ofEpochSecond(
1_570_406_400L
)
.atOffset(
ZoneOffset.UTC
)
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
07-10-2019
Avoid legacy classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes.
java.time
Parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC as a Instant.
Is your example value correct? Perhaps you meant 1,570,406,400.
long seconds = 1_570_406_400L ;
Instant instant = Instant.ofEpochMilli( seconds ) ;
The Instant represents a moment in UTC. Generate a string representing this value in standard ISO 8601 format.
String output = instant.toString() ;
instant.toString(): 2019-10-07T00:00:00Z
To adjust to another time zone, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2019-10-06T20:00-04:00[America/Montreal]
Notice how the date is the 6th rather than the 7th. While at that moment a new day has begun in UTC, it is still “yesterday” in Canada. For any given moment, the date varies around the globe by time zone.
Generate a string a localized format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
String output = zdt.format( f ) ;
output: 06-10-2019
If you want to report the date as seen in UTC rather than a time zone, use OffsetDateTime class. Specify UTC using the constant ZoneOffset.UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
String output = odt.format( f ) ;
outputOdt: 07-10-2019
See all that code run live at IdeOne.com.
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.

Get Date from a DataObject (SDO) without losing the hour (JAVA)

I'm trying to get a date from a DataObject (Service Date Object (SDO)) that comes to me as an input and insert it into an Oracle database. The problem has been that the Date I get does not seem to have the introduced hour.
I am using the setDate() method from DataObject with the following value: 2019-05-22T13:30:00Z.
For some reason, when using getDate() what is returning is the day entered with the hour set at 0 (2019-05-22 00:00:00).
I'm not sure if it's due to the input format or something related to the Date class from java.utils.
An easy solution would be to pass it as String and convert it into Date using a format but I would like to save this intermediate step.
java.util.Date versus java.sql.Date
Your Question does not provide enough detail to know for sure, but I can take an educated guess.
returning is the day entered with the hour set at 0 (2019-05-22 00:00:00).
I suspect your code calling setDate and/or getDate is using a java.sql.Date object rather than a java.util.Date object.
➥ Check your import statements. If you used the wrong class by accident, that would explain the time-of-day getting set to 00:00.
java.util.Date represents a moment in UTC (a date, a time-of-day, and an offset-from-UTC of zero hours-minutes-seconds).
java.sql.Date pretends to represent a date-only, without a time-of-day and without a time zone or offset-from-UTC. Actually does contain a time-of-day and offset, but tries to adjust the time to 00:00:00.0 as part of the pretense.
Confusing? Yes. These old date-time classes from the earliest days of Java are a bloody awful mess, built by people who did not understand the complexities of date-time handling. Avoid these legacy date-time classes!
These legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310. Try to do all your work in java.time. When interoperating with old code such as SDO that is not yet updated for java.time, call on new conversion methods added to the old classes.
The modern replacement of a java.util.Date is java.time.Instant. Both represents a moment in UTC, though Instant has a finer resolution of nanoseconds versus milliseconds.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Convert from modern class to legacy class. Beware of data-loss: Any microseconds or nanoseconds in the fractional second are truncated to milliseconds (as noted above).
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern to legacy. Truncates any microseconds or nanoseconds.
Pass to your SDO object.
mySdoDataObject.setDate( d ) ;
Going the other direction, retrieve the legacy java.util.Date object and immediately convert to an Instant.
Instant instant = mySdoDataObject.getDate().toInstant() ;
To see that same moment through the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
An easy solution would be to pass it as String
No! Use smart objects, not dumb strings. We have the industry-leading date-time library built into Java, so use it.
Database
As of JDBC 4.2, we can directly exchange java.time objects with the database.
Your JDBC driver may optionally handle Instant. If not, convert to OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;
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.

Inserting into database a datetime with the current UTC time

I'm attempting to insert a datetime into a mysql database for the current UTC time via the GETUTCDATE() function in sql. It's failing with "FUNCTION GETUTCDATE DOES NOT EXIST".
Is a way for me to get the current UTC time in sql datetime format from Java, and simply insert it as a string?
Another big issue I'm having is I need to convert the above utc datetime object into local time zones and I don't really know how to do that through standard java api's.
tl;dr
myPreparedStatement // Using a `PreparedStatement` avoids SQL-injection security risk.
.setObject( // As of JDBC 4.2, we can exchange java.time objects with a database via `getObject`/`setObject` methods.
… , // Indicate which `?` placeholder in your SQL statement.
OffsetDateTime.now( ZoneOffset.UTC ) // Capture the current moment in UTC.
) ;
java.time
The modern solution uses the java.time classes that years ago supplanted the terrible old date-time classes.
Get the current moment in UTC using OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
MySQL 8.0 uses a resolution of microseconds, for six decimal places in a fractional second. The java.time classes carry a finer resolution of nanoseconds. So you may want to truncate any existing nanos from your OffsetDateTime. Specify your desired resolution with ChronoUnit.
OffsetDateTime odt =
OffsetDateTime
.now(
ZoneOffset.UTC
)
.truncatedTo( ChronoUnit.MICROS )
;
Send to your database via a PreparedStatement to a column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE data type. For MySQL 8.0, that would be the type TIMESTAMP.
myPreparedStatement.setObject( … , odt ) ;
And retrieval via a ResultSet.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
To see this moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ; // Same moment, same point on the timeline, different wall-clock time.
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.
You can do it as follows:
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
String sql_date = utc.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); //here, you can change the format of SQL date as you need
You would need to import the classes as follows:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
Hope it helps.

Convert java.sql.Timestamp to Java 8 ZonedDateTime?

Migrating Joda time to Java 8
Joda:
UserObject user = new UserObject()
user.setCreatedAt(new DateTime(rs.getTimestamp("columnName")));`
Migrating to Java 8
This is my code; it does compile; I am doubtful if it works:
ZonedDateTime.ofInstant(rs.getTimestamp("columnName").toLocalDateTime().toInstant(ZoneOffset.UTC),ZoneId.of("UTC")));
In some cases, the date is wrong. Any advice?
tl;dr
To track a moment in history, use Instant as the type of your class member variable. Specifically, this moment is seen as a date and time-of-day in UTC.
public class UserObject() {
Instant createdAt ;
…
public void setCreatedAt( Instant instantArg ) {
this.createdAt = instantArg ;
{
}
Usage, capturing the current moment.
UserObject user = new UserObject() ;
user.setCreatedAt( Instant.now() ) ;
Usage, populating value from database.
UserObject user = new UserObject() ;
Instant instant = myResultSet.getObject( "when_created" , Instant.class ) ;
user.setCreatedAt( instant ) ;
JDBC 4.2 does not require support for Instant (a moment in UTC). If your driver does not support that class, switch to OffsetDateTime which is required.
UserObject user = new UserObject() ;
OffsetDateTime odt = myResultSet.getObject( "when_created" , OffsetDateTime.class ) ;
user.setCreatedAt( odt.toInstant() ) ; // Convert from an `OffsetDateTime` (for any offset-from-UTC) to `Instant` (always in UTC).
Present to the user, localized for the user-interface.
user // Your business object.
.getCreatedAt() // Returns a `Instant` object.
.atZone( // Adjust from UTC to a time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Pacific/Auckland" ) // Specify the user’s desired/expected time zone.
) // Returns a `ZonedDateTime` object.
.format( // Generate a `String` representing the value of date-time object.
DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.FULL // Specify how long or abbreviated the string.
)
.withLocale( // Specify `Locale` to determine human language and cultural norms for localization.
Locale.CANADA_FRENCH
)
) // Returns a `String`.
Notice that Locale has nothing to do with time zone, an orthogonal issue. The code above might be for a business person from Québec who is traveling in New Zealand. She wants to see the wall-clock time used by the kiwis around her, but she prefers to read its textual display in her native French. Both time zone and locale are issues best left to presentation only; generally best to use UTC in the rest of your code. Thus, we defined our member variable createdAt as an Instant, with Instant always being in UTC by definition.
Avoid java.sql.Timestamp
The java.sql.Timestamp, along with java.sql.Date, java.util.Date, and Calendar are all part of the terribly troublesome old date-time classes that were supplanted years ago by the java.time classes.
Joda-Time too is now supplanted by the java.time classes, as stated in the front page of the project’s site.
java.time
As of JDBC 4.2 and later, we can directly exchange java.time objects with the database.
Instant
Send the current moment to the database using Instant class. 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).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime
To see that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
LocalDateTime is not a moment
.toLocalDateTime().
Never involve LocalDateTime class when representing a specific moment in time. The class purposely lacks any concept of time zone or offset-from-UTC. As such, it cannot represent a moment, is not a point on the timeline. It is a vague idea about potential moments along a range of about 26-27 hours (the range of time zones).
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
This seems to work:-
ZonedDateTime.ofInstant(rs.getTimestamp("columnname").toInstant(), ZoneId.of("UTC"))
Use the following:
rs.getTimestamp("columnName").toInstant()
.atZone(ZoneId.[appropriate-zone-ID-here])
You need to use a ZoneId appropriate to the region (you may try with ZoneId.systemDefault() for a start).
For more details about the differences between various Java-Time APIs, see this great answer.

How can I tell if a Java Date and time zone is before the current time?

My class has 2 properties that make up its date:
java.util.Date date;
String timeZone;
How can I see if this date is before the current time on the server?
Basically I want to write something like this, but take timeZone into account:
return date.before(new Date());
Date stores internally as UTC, so your timeZone variable is not necessary. You can simply use Date.before(Date).
Calendar startCalendar = Calendar.getInstance();
int startTimeZoneOffset = TimeZone.getTimeZone(timeZone).getOffset(startDate.getTime()) / 1000 / 60;
startCalendar.setTime(startDate);
startCalendar.add(Calendar.MINUTE, startTimeZoneOffset);
Calendar nowCalendar = Calendar.getInstance();
int nowTimeZoneOffset = nowCalendar.getTimeZone().getOffset(new Date().getTime()) / 1000 / 60;
nowCalendar.setTime(new Date());
nowCalendar.add(Calendar.MINUTE, nowTimeZoneOffset);
return startCalendar.before(nowCalendar);
tl;dr
Use Instant class, which is always in UTC. So time zone becomes a non-issue.
someInstant.isBefore( Instant.now() )
java.time
The modern approach uses the java.time classes that supplanted the terrible Date & Calendar classes.
As the correct Answer by Kuo stated, your java.util.Date is recording a moment in UTC. So no need for a time zone.
Likewise, its replacement, the java.time.Instant class, also records a moment in UTC. So no time zone needed.
Instant instant = Instant.now() ; // Capture current in UTC.
So all you need as member variables on your class is Instant.
public class Event {
Instant when ;
…
}
To compare Instant objects, use the isAfter, isBefore, and equals methods.
someInstant.isBefore( Instant.now() )
For presentation in a time zone expected by the user, assign a ZoneId to get a ZonedDateTime object. The Instant and the ZonedDateTime both represent the same moment, the same point on the timeline, but viewed through different wall-clock time.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
String output = zdt.toString() ; // Generate text in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
Or let java.time automatically localize output. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l );
String output = zdt.format( f );
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.

Categories

Resources