Java: Error while saving date value to database(Simpledataformat) - java

I am trying to save a date in DB but i am getting the below error. I am confused because i am sending the same format but still throwing exception:
java.lang.IllegalArgumentException: Timestamp format must be
yyyy-mm-dd hh:mm:ss[.fffffffff]
If i am trying in SQL Developer in the below way it works fine
to_date('01/01/1900', 'mm/dd/yyyy')
Through java i tried doing as below
First Method
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date myDate = format1.parse("01/01/1900 00:00:00");
Second Method
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = format1.parse("01/01/1900");
Where am i going wrong.
P.S : Please before marking it as duplicate and stopping people from answering question understand i have tried something and got the error.

tl;dr
myPreparedStatement.setObject(
… ,
LocalDate.parse(
"01/01/1900" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
)
Details
The Answer by Just another Java programmer is correct.
Furthermore, you should not use strings to communicate date-time values with a database. Use date-time classes.
The modern way is with java.time classes, supplanting the troublesome legacy date-time classes.
LocalDate
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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You can parse directly from a string in standard ISO 8601 format.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Or specify each part.
LocalDate localDate = LocalDate.of( 2016, Month.JANUARY , 23 );
To parse other formats, use DateTimeFormatter class. Search Stack Overflow for many examples.
Database
If your JDBC driver complies with JDBC 4.2 or later, it should be able to pass a java.time type with PreparedStatement::setObject and fetch with ResultSet::getObject.
myPreparedStatement.setObject( … , localDate );
…or…
myPreparedStatement.setObject( … , localDate , JDBCType.DATE );
If your driver is not so enabled, fall back to using java.sql.Date. This awkward class pretends to represent a date-only value (but actually has a time component set to midnight which we are supposed to ignore). To convert to/from java.time look to new methods added to the old classes.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Pass to PreparedStatement::setDate.
myPreparedStatement.setDate( … , sqlDate );
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.

Your date pattern does not match.
Better is to use a PreparedStatement so you never will rely on string conversion.

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.

how to mock timestamp and date function in 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.

Date operations in Java already passed or near in the future

In Java (I'm a junior) - how do you perform various date operations?
Assess "storedDate is one week away from today" and "storedDate has passed"
I am not sure if its the best approach or how to do the condition check
java.sql.Date dueDate = (Date) loggedUser.get("dueDate");
I've seen various calculations like this - but not sure an if condition could be met like this?
Calendar c= Calendar.getInstance();
//c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(c.getTime()));// This past Sunday [ May include today ]
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime()));// Next Sunday
Step 1: Learn to read API pages.
Here is the Calendar API Page, read it.
For your class project, you don't care about timezone (since you didn't mention it in your post).
Get a date parameter: public void methodName(Date dateParameter)
Create a Calendar containing now: Calendar myCalendar = Calendar.getInstance();
Set a calendar to a date value: myCalendar.setTime(dateParameter)
"Calculate" one week from today: myCalendar.roll(Calendar.DAY_OF_YEAR, 7)
The Calendar object stores Millisecond, Second, Minute, and Hour.
Clear these using the set method.
Compare Calendar objects using the after method.
tl;dr
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
.with(
TemporalAdjusters.previousOrSame​( DayOfWeek.SUNDAY )
)
java.time
The modern approach uses java.time classes.
Get current moment in UTC.
Instant instant = Instant.now() ;
If you care about day-of-week, you care about date. Determining a date requires a time zone. For any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same point on the timeline, different wall-clock time.
To focus on date-only without time-of-day, extract a LocalDate.
LocalDate ld = zdt.toLocalDate() ;
To adjust into other moments, use a TemporalAdjuster. Find implementations in TemporalAdjusters.
LocalDate previousOrSameSunday = ld.with(
TemporalAdjusters.previousOrSame​( DayOfWeek.SUNDAY )
) ;
…and…
LocalDate nextOrSameSunday = ld.with(
TemporalAdjusters.nextOrSame​( DayOfWeek.SUNDAY )
) ;
To compare, look for isBefore, isAfter, isEqual, and equals methods on the various java.time classes.
thisLocalDate.isBefore( thatLocalDate)
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.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.

String to Cassandra Timestamp

I want to convert string date to Cassandra time stamp format
Example date
String inputDate="20170525"
You need to convert your string to Date.
Java Date type maps cassandra timestamp type
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = dateFormat.parse("20170525");
Now you have the date you can insert or query with it in prepared statement
Note : You don't have any timezone. So default timezone will be used. If you want to specify the timezone use dateFormat.setTimeZone(TimeZone zone) method
First, parse that input string as a LocalDate.
LocalDate ld = LocalDate.parse( "20170525" , DateTimeFormatter.BASIC_ISO_DATE ) ;
For a date-only value without time-of-day, you should be using type Date in Cassandra according to this documentation.
You can exchange data as strings using standard ISO 8601 format. The java.time classes use the standard formats by default. So no need to specify a formatting pattern.
String output = ld.toString() ;
2017-05-25
If you really want to store in the timestamp, you must specify a time-of-day. Perhaps you want the first moment of the day. Determining that specific moment on the timeline that requires a time zone. Do not assume the first moment occurs at 00:00:00. Anomalies such as Daylight Saving Time mean the time may be another value such as 01:00:00.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2017-05-25T00:00:00-04:00[America/Montreal]
Cassandra stores the Timestamp field only as UTC. So we need to adjust the ZonedDateTime from our desired time zone to UTC. The easiest way to do that is extract a Instant. The Instant class is always in UTC by definition.
Instant instant = zdt.toInstant() ;
Generate a string in standard ISO 8601 format for Cassandra. Notice how the hour jumps from zero to four. Our time zone America/Montreal is four hours behind UTC on that date. So getting to UTC means adding four hours, 0 + 4 = 4.
String output = instant.toString() ;
2017-05-25T04:00:00Z
Going the other way when your retrieve this value.
Instant instant = Instant.parse( "2017-05-25T04:00:00Z" ) ;
ZonedDateTime zdt = instant.atZone( 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.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.

Date Conversion in Spring is one day off

I have a POST end-point that takes a couple of values, one being endDate and startDate. When the JSON posts in as:
{ "startDate" : "2015-01-30", "endDate" : "2015-12-30" }
Spring converts it to a java.util.Date Object that is always one day behind. In the logs I see:
Validating that startDate Thu Jan 29 16:00:00 PST 2015 < endDate Tue Dec 29 16:00:00 PST 2015
So it got the timezone correct. I had assumed it was related to UTC conversions, but I'm not sure how to configure this or modify it so that it converts it using the proper off-set. The timestamp portion of it isn't required - I only care that the year, day, and month match what is passed in.
if it matters, I'm using Spring (happened with 4.0.6 and 4.1.7) and a POST
tl;dr
LocalDate.parse( "2015-01-30" )
Use the right data type for the job
You are trying to fit a date-only value into a date-time type, java.util.Date. Square peg, round hole. While trying to come up with a time-of-day to associate with your date, a time zone is being injected, hence your problem.
LocalDate
Solution:
Never use the terrible old legacy date-time classes such as java.util.Date. Use only the modern java.time classes.
For a date-only value, use LocalDate.
Your input string happens to be in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2015-01-30" ) ;
ZonedDateTime
If you want a moment, a date with a time-of-day, let java.time determine the first moment of the day. Never assume that moment is 00:00:00. In some zones on some dates it may be another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
ZonedId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of that date in that zone.
Instant
To adjust from to UTC (same moment, different wall-clock time), extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust to UTC. Same moment, same simultaneous 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.
String str="2015-01-30";
try{
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
isoFormat.setTimeZone(TimeZone.getTimeZone("PST"));
Date date = isoFormat.parse(str);
System.out.println(date);
}catch(ParseException e){
e.printStackTrace();
}
Check here http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-webdatabinder how to customize automatic Spring conversion:
#Controller
public class MyFormController {
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}

Categories

Resources