tl;dr
ZonedDateTime.now() // Capture the current moment as seen by the people of a region representing by the JVM’s current default time zone.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).
java.time
The modern approach uses the java.time classes.
Capture the current moment in UTC.
Instant instant = Instant.now() ;
View that same moment through the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
You want to generate a string representing this value in a format that lacks any indication of time zone or offset-from-UTC. I do not recommend this. Unless the context where read by the user is absolutely clear about the implicit zone/offset, you are introducing ambiguity in your results. But if you insist, the java.time classes predefine a formatter object for that formatting pattern: DateTimeFormatter.ISO_LOCAL_DATE_TIME
.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_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?