tl;dr
Use modern LocalDate
class.
LocalDate.parse( // Represent a date-only value without time-of-day and without time zone in `java.time.LocalDate` class.
"I am Going to join in scholl at 21/10/2108". // Split your input string, looking for last part separated by a SPACE.
.substring(
"I am Going to join in scholl at 21/10/2108".lastIndexOf( " " )
+ 1
)
,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Specify formatting pattern to match your input. Tip: Use ISO 8601 formats instead.
)
.toString() // Generate text in standard ISO 8601 format.
2108-10-21
Splitting string
First split the string into pieces.
String input = "I am Going to join in scholl at 21/10/2108";
String[] parts = input.split( " " );
Look at those parts.
for ( String part : parts ) {
System.out.println( part );
}
I
am
Going
to
join
in
scholl
at
21/10/2108
Extract the last part.
String part = parts[ parts.length - 1 ]; // Subtract 1 for index (annoying zero-based counting).
LocalDate
The modern approach uses the java.time classes. Specifically, LocalDate
for a date-only value without time-of-day and without time zone or offset-from-UTC.
Parse that last part as a LocalDate
. Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( part , f );
ISO 8601
Whenever possible, do not exchange date-time values textually using formats intended for presentation to humans.
Instead, use formats defined for the purpose of data-interchange in the ISO 8601 standard. For a date-only value, that would be: YYYY-MM-DD
The java.time classes use the ISO 8601 formats by default when parsing/generating text.
String output = LocalDate.now().toString()
2018-01-23
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.