tl;dr
ZonedDateTime.now( ZonedId.of( "America/Montreal" ) ).format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " )
Details
Which is the solution of this problem? For month I think I have to add 1,right?
Nope, not if you use better classes. You are using troublesome, confusing, poorly designed date-time classes which should be avoided. Instead use java.time classes.
ZonedDateTime
Get the current moment in your desired/expected time zone. Get a ZonedDateTime
object.
ZoneId zoneId = ZonedId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
Interrogate for the parts if that is what you need. The java.time classes count month sensibly, 1-12 is January-December. By the way, check out the handy Month
enum.
int month = zdt.getMonthValue();
int dayOfMonth = zdt.getDayOfMonth();
To get literally the string you showed, let the DateTimeFormatter
class do the work. The predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
gets you nearly there. You can replace the T
in the middle with a SPACE to finish.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.