tl;dr
The modern approach uses java.time classes.
LocalDate
.now
(
ZoneId.of( "Africa/Casablanca" )
)
.format
(
DateTimeFormatter.ofPattern( "dd/MM/uu" )
)
Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
For a date only value, without a time-of-day and without a time zone, use LocalDate
.
A time zone is required to determine the current date. For any given moment, the date may by “tomorrow” in Japan while still “yesterday” in Mexico.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
Generate a string with text in standard ISO 8601 format.
String output = ld.toString() ;
Generate a string with text in your custom format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uu" ) ;
String output = ld.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
.
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?