Unmarshalling JSON sql Date fields from servlet, mine gets date wrong? - java

I am using JSON to get data from an HttpServlet for data object class definitions that are shared between the servlet and a java client. If I print out the response from the api call I can see that the instance variable is correct. Then when I map it using Jackson object mapper and look at the instance the value is wrong, always by one day lower then the date in the response and in the database.
The response looks like:
[{"coveragePK":3,"agentPK":2,"serviceCoveragePK":12,
"coverageDate":"2018-02-27","duration":10,"remainder":1,
"startTime":"07:30:00","query":""},
{"coveragePK":4,"agentPK":2,"serviceCoveragePK":13,
"coverageDate":"2018-02-27","duration":8,"remainder":2,
"startTime":"10:00:00","query":""}]
and after I map it I get:
Date: 2018-02-26 which is printed with
java.sql.Date date = coverages[i].getCoverageDate();
System.out.println("Date: " + date.toString());
If I convert the sql.Date to a LocalDate the result is the same as one would expect.
I use the following to write the json where coverages is an ArrayList.
ObjectMapper mapper = new ObjectMapper();
String psWindows = mapper.writeValueAsString(coverages);
PrintWriter out = httpServletResponse.getWriter();
out.append(psWindows);
And I read the JSON with
ObjectMapper mapper = new ObjectMapper();
CoverageDO[] coverage = mapper.readValue(foo, CoverageDO[].class);

I suspect the problem is in your timezone.
java.sql.Date stores the date like a timestamp (time since January 1, 1970, 00:00:00 GMT), but when it gets converted to java.util.Date. Try to use SimpleDateFormat to check the real date.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(date);

tl;dr
LocalDate.parse( "2018-02-27" )
java.time
The java.sql.Date class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate ld = LocalDate.parse( "2018-02-27" ) ;
LocalTime lt = LocalTime.parse( "10:00:00" ) ;
Generate a string representing that date’s value using standard ISO 8601 format by calling toString.
String output = ld.toString() ;
2018-02-27
Put those two together.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
ldt.toString(): 2018-02-27T10:00:00
A LocalDateTime lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. It represents a vague idea of potential moments along a range of about 26-27 hours.
To determine an actual moment, place it into the context of a time zone (or offset) if you are absolutely certain such a zone/offset was intended.
If I convert the sql.Date to a LocalDate
Don’t. No need to ever use java.sql.Date again. Just use LocalDate.
If you must inter-operate with old code not yet updated to java.time classes, then call new conversion methods added to the old classes.
LocalDate ld = myJavaSqlDate.toLocalDate() ; // From legacy class to modern class.
java.sql.Date myJavaSqlDate = java.sql.Date.valueOf( ld ) ; // Vice-versa. From modern class to legacy 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, 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

Parse timestamp string to Java.sql.timestamp [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Java: Convert String to TimeStamp
(11 answers)
Closed 3 years ago.
I have the following timestamp in String format
2019-04-06T00:43:21+00:00
2019-04-04T21:24:33+00:00
2019-04-04T21:02:16+00:00
How can I parse the timestamp strings above to Java.sql.timestamp?
Use DateFormat to parse your String.
try{
String x="2019-04-04T21:24:33+00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date date = (Date) df.parse(x);
java.sql.Timestamp timeStamp = new java.sql.Timestamp(date.getTime());
}catch(ParseException pe){
pe.printStackTrace();
}
As mentioned by others in comments, there is a more updated way to do this.
String time="2019-04-04T21:02:16+00:00";
OffsetDateTime odt=OffsetDateTime.parse(time,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
java.sql.Timestamp timestamp=new java.sql.Timestamp(odt.toEpochSecond()*1000);
tl;dr
Timestamp // Avoid this terrible legacy class if possible. Represents a moment in UTC.
.from( // Convert from modern `Instant` to legacy `Timestamp`. No data loss, as both resolve to nanoseconds.
OffsetDateTime // Modern way to represent a moment with an offset-from-UTC (hours, minutes, and seconds).
.parse( "2019-04-06T00:43:21+00:00" ) // Parse standard ISO 8601 strings. Returns a `java.time.OffsetDateTime` object.
.toInstant() // Extract an `Instant` from the `OffsetDateTime`, thereby adjusting to UTC (an offset of zero).
) // Returns a `Timestamp` object, if needed to interoperate with old code not yet updated to *java.time*.
Even better, skip the terrible Timestamp class entirely.
myPreparedStatement.setObject( // As of JDBC 4.2 and later, exchange *java.time* objects with your database.
1 , // Specify the nth placeholder in your SQL statement.
OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) // Parse an ISO 8601 compliant string as a `OffsetDateTime` object, a moment with an offset-from-UTC. Pass to the database via the `setObject` call.
)
OffsetDateTime
Your input strings indicate an offset-from-UTC (a number of hours-minutes-seconds), that part at the end.
Your input strings are in standard ISO 8601 format. The java.time classes use these formats by default in parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) ;
java.sql.Timestamp
Never use java.util.Timestamp. That terrible class was supplanted years ago by the modern java.time classes.
If you must have a Timestamp object to interoperate with old code not yet updated to java.time, convert by calling new methods added to the old classes. Extract a Instant from the OffsetDateTime (thereby adjusting from any offset to an offset of zero, for UTC itself). Pass the Instant object to Timestamp.from.
java.sql.Timestamp ts = Timestamp.from( odt.toInstant() ) ;
JDBC 4.2
As of JDBC 4.2, we can exchange java.time objects with the database.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
All this has been covered many many times already on Stack Overflow. So search for more info. And in the future, search thoroughly before posting.
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.

Why aren't milliseconds excluded from JSON when using dateFormat in Jackson's ObjectMapper with Java 8 dates?

I am trying to figure out why Jackson (2.9.5) formats dates from Java 8 incorrectly.
data class Test(
val zonedDateTim: ZonedDateTime = ZonedDateTime.now(),
val offsetDateTim: OffsetDateTime = OffsetDateTime.now(),
val date: Date = Date(),
val localDateTime: LocalDateTime = LocalDateTime.now()
)
val mapper = ObjectMapper().apply {
registerModule(KotlinModule())
registerModule(JavaTimeModule())
dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
enable(SerializationFeature.INDENT_OUTPUT)
}
println(mapper.writeValueAsString(Test()))
From the date format I provided I would expect to get dates formatted without milliseconds but instead the result looks like this:
{
"zonedDateTim" : "2018-07-27T13:18:26.452+02:00",
"offsetDateTim" : "2018-07-27T13:18:26.452+02:00",
"date" : "2018-07-27T13:18:26",
"localDateTime" : "2018-07-27T13:18:26.452"
}
Why are milliseconds being included in the formatted dates?
dateFormat only applies to Date objects - the 3 other objects are handled by the JavaTimeModule, which uses ISO formatting by default.
If you want a different format, you can use:
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
val javaTimeModule = JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, LocalDateTimeSerializer(format));
javaTimeModule.addSerializer(ZonedDateTime.class, ZonedDateTimeSerializer(format));
mapper.registerModule(javaTimeModule);
You may also need to add mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); but I'm not 100% sure that it's necessary.
Also note that with that format, you will lose time zone and offset information. So you may want a different format for Offset/Zoned-DateTimes.
The Answer by assylias is correct. Here are some further thoughts.
Truncate
If you really do not want the fractional second at all, truncate to whole seconds.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;
OffsetDateTime odt = OffsetDateTime.now().truncatedTo( ChronoUnit.SECONDS ) ;
ZonedDateTime zdt = ZonedDateTime.now().truncatedTo( ChronoUnit.SECONDS ) ;
The formatters used by the various toString methods by default omit any text representing the fractional second if the value is zero.
So the value of:
2018-07-27T13:18:26.452+02:00
…becomes:
2018-07-27T13:18:26.000+02:00
…and its String representation will be generated as seconds without a fraction:
2018-07-27T13:18:26+02:00
Try it.
OffsetDateTime odt = OffsetDateTime.parse( "2018-07-27T13:18:26.452+02:00" ) ;
OffsetDateTime odtTrunc = odt.truncatedTo( ChronoUnit.SECONDS ) ;
System.out.println( "odt.toString(): " + odt ) ;
System.out.println( "odtTrunc.toString(): " + odtTrunc ) ;
Try that code live at IdeOne.com.
odt.toString(): 2018-07-27T13:18:26.452+02:00
odtTrunc.toString(): 2018-07-27T13:18:26+02:00
Avoid legacy classes
The code in your Question confuses me. Do not mix the troublesome old legacy date-time classes such as Date & SimpleDateFormat with the modern java.time classes. The legacy classes are entirely supplanted by the modern ones.
Timeline
Be clear that LocalDateTime serves a very different purpose than Instant, OffsetDateTime, and ZonedDateTime. A LocalDateTime object purposely lacks any concept of time zone or offset-from-UTC. So it cannot represent a moment, is not a point on the timeline.
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.

XMLGregorianCalendar date format 'dd/MM/yyyy HH:mm:ss.SSS'

String formatA ="yyyy-MM-dd'T'HH:mm:ss'Z'";
String formatB = "dd/MM/yyyy HH:mm:ss.SSS";
try {
XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat(formatB).format(new Date()));
System.out.println(gregFmt);
} catch (DatatypeConfigurationException e) {
};
I am trying to formate XMLGregorianCalendar date .
The above code formats well for format "yyyy-MM-dd'T'HH:mm:ss'Z'"
But for formatB dd/MM/yyyy HH:mm:ss.SSS it throws error
java.lang.IllegalArgumentException
Do advice on how to fix it. Thank you so much!
log
Exception in thread "main" java.lang.IllegalArgumentException: 23/08/2017 16:13:04.140
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parseAndSetYear(XMLGregorianCalendarImpl.java:2887)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parse(XMLGregorianCalendarImpl.java:2773)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.<init>(XMLGregorianCalendarImpl.java:435)
at com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl.newXMLGregorianCalendar(DatatypeFactoryImpl.java:536)
at test.test.main(test.java:19)
line19 is line 4 , in the above code 'XMLGregorianCalendar gregFmt...'
The format that newXMLGregorianCalendar(string) accept is described in the XML specs and is different from the formatB you are trying to use.
tl;dr
Date-time objects do not have a “format”. They parse & generate String objects representing textually their value.
Use the modern java.time that replaced terrible old classes Date & XMLGregorianCalendar classes.
Example:
myXMLGregorianCalendar // If you must use this class… but try to avoid. Use *java.time* classes instead.
.toGregorianCalendar() // Converting from `javax.xml.datatype.XMLGregorianCalendar` to `java.util.GregorianCalendar`.
.toZonedDateTime() // Converting from `java.util.GregorianCalendar` to `java.time.ZonedDateTime`, from legacy class to modern class.
.format( // Generate a `String` representing the moment stored in our `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) // Define a formatting pattern as you desire. Or better, automatically localize by calling `DateTimeFormatter.ofLocalized…` methods.
) // Returns a `String` object, distinct from our `ZonedDateTime` object.
07/07/2018 15:20:14.372
Date-time objects do not have a format
Do not conflate date-time objects with the strings they generate to represent their value. Date-time values, including the classes discussed below, are not a String, do not use text as their internal value, and do not have a “format”. All of them can generate, and parse, strings to represent their date-time value.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as XMLGregorianCalendar.
The use of java.util.Date should be replaced with java.time.Instant. Both represent a moment in UTC. Instant uses a finer resolution of nanoseconds rather than milliseconds.
You can easily convert between the modern and legacy classes. Notice the new conversion methods added to the old classes, in this case java.util.GregorianCalendar::toZonedDateTime.
First convert from javax.xml.datatype.XMLGregorianCalendar to java.util.GregorianCalendar.
GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Now get out of these legacy classes, and into java.time.
ZonedDateTime zdt = gc.toZonedDateTime() ;
All three types so far, the XMLGregorianCalendar, the GregorianCalendar, and the ZonedDateTime all represent the same moment, a date with time-of-day and an assigned time zone.
With a ZonedDateTime in hand, you can generate a String in standard ISO 8601 format extended to append the name of the time zone in square brackets.
String output = zdt.toString() ; // Generate string in standard ISO 8601 format extended by appending the name of time zone in square brackets.
2018-07-07T15:20:14.372-07:00[America/Los_Angeles]
You can generate strings in other formats using DateTimeFormatter class. For the formatting pattern listed second in your question, define a matching DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) ;
String output = zdt.format( f ) ;
07/07/2018 15:20:14.372
The first formatting pattern listed in your Question has a Z on the end, which means UTC and is pronounced “Zulu”. To adjust our ZonedDateTime to UTC, simply extract a Instant object. An Instant is always in UTC by definition.
Instant instant = zdt.toInstant() ; // Extract an `Instant` object, always in UTC.
Generate a String in the pattern shown first in the Question.
String output = instant.toString() ; // Generate string in standard ISO 8601 format.
2018-07-07T22:20:14.372Z
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.

While converting String to Date got ambiguity between java.util.Date and java.sql.Date

I am trying to get date as input from Date tag of HTML
Birth Date <input type="date" name="dob"/>
and accessing on jsp page by using
String strDate = request.getParameter("dob");
but it returns in the format of string and I wanted to convert it in to date, I have tried as follows
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(strDate);
But it gives error
incompatible types required: java.sql.Date found: java.util.Date
and when I imported pakage "java.util.*" for using java.util.Date date = sdf.parse(strDate); it gives
reference to Date is ambiguous, both class java.util.Date in java.util and class java.sql.Date in java.sql match
If you need a java.sql.Date (and incompatible types required: java.sql.Date found: java.util.Date indicates you do), remove the import of java.util.Date and use the java.util.Date returned by the DateFormat to construct a java.sql.Date with something like
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = new Date(sdf.parse(strDate).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
tl;dr
LocalDate.parse( "2018-01-23" )
Details
The Answer by Elliott Frisch is correct. One comment there asked if is there is a better conversion recommended. There is indeed a better way. Bonus: that better way avoids the original problem, confusing java.util.Date with java.sql.Date.
java.time
The java.time framework built into Java 8 and later supplants the poorly-designed troublesome old java.util.Date/.Calendar classes and their kin. The new classes are inspired by the highly successful Joda-Time framework, similar in concept but re-architected. Defined by JSR 310. See the Oracle Tutorial. Extended by the ThreeTen-Extra project. Back-ported to Java 6 & 7 by the ThreeTen-Backport project, which is wrapped for use in Android by the ThreeTenABP project.
The LocalDate class represents a date-only value, without time-of-day and without time zone.
ISO 8601
Your input string happens to comply with the ISO 8601 standard.
This standard is used by default in the java.time classes for parsing/generating date-time strings. So no need to specify a formatting pattern.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Database
As of JDBC 4.2 and later, you can exchange java.time objects directly with your database via getObject/setObject methods.
JDBC 4.2 and later
Insert/Update.
myPreparedStatement.setObject( … , localDate ) ;
Retrieval.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
JDBC 4.1 and earlier
If your JDBC driver is not yet updated for JDBC 4.2 or later, convert between java.time and java.sql types. The old java.sql classes have new methods for such conversions.
For LocalDate, convert to/from the java.sql.Date class (which pretends to be a date-only value).
java.sql.Date mySqlDate = java.sql.Date.valueOf( localDate );
…and going the other direction…
java.time.LocalDate localDate = mySqlDate.toLocalDate();
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.

Problem adding minutes with plusMinutes

I'm trying to add some minutes to a date using plusMinutes, but it just doesn't add anything at all:
Here's the code:
String currentDate ;
SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date1= null;
DateTime dt;
currentDate ="27/12/2010 11:29" ;
try {
date1= myFormat.parse(currentDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
dt = new DateTime(date1);
dt.plusMinutes(30);
Javadoc says
Returns a copy of this datetime plus the specified number of millis.
so
do something like
dt = new DateTime(date1);
dt = dt.plusMinutes(30);
System.out.println(""+dt);
Beauty of joda is that most of their classes are immutable like String in Java. Update operations doesn't change the original object. So plusMinutes(...) returns a new copy of the DateTime with the minutes added which you can assign to a new variable as shown below.
DateTime newDt=dt.plusMinites(30);
System.out.println(newDt);
I think you want dt = dt.plusMinutes(30);
plusMinutes returns a calculated dateTime. It does not modify the dateTime it is called on.
tl;dr
java.time.LocalDateTime.parse(
"27/12/2010 11:29" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm" )
).plusMinutes( 30 )
2010-12-27T11:59
Tip: If you intended this to be a moment, a specific point on the timeline, apply the context of a time zone (ZoneId) to get a ZonedDateTime.
java.time
Your Question uses the troublesome old date-time classes from the earliest versions of Java, and your Question uses the Joda-Time project which is now in maintenance mode. Both have been supplanted by the java.time classes built into Java 8 and later.
Your string input lacks an indicator of time zone or offset-from-UTC. So parse as a java.time.LocalDateTime.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm" ) ;
LocalDateTime ldt = LocalDateTime.parse( "27/12/2010 11:29" , f ) ;
ldt.toString(): 2010-12-27T11:29
Note that you do not have an actual moment, this is not a specific point on the timeline. This is only a vague idea about potential moments along a range of about 26-27 hours. To determine an actual moment, place this in the context of a time zone (or offset): ZonedDateTime zdt = ldt.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;.
Add your minutes.
LocalDateTime later = ldt.plusMinutes( 30 ) ;
later.toString(): 2010-12-27T11:59
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