GregorianCalendar in Android (add Calendar.HOUR_OF_DAY vs Calendar.HOUR) - java

To add an hour to current time, can I use this?
Calendar mcalendar = new GregorianCalendar();
mcalendar.add(Calendar.HOUR_OF_DAY, 1); //I plan to use 24 hours format
I see many examples using instead:
Calendar mcalendar = Calendar.getInstance();
mcalendar.add(Calendar.HOUR, 1);

tl;dr
Duration duration = Duration.ofHours( 1 ) ;
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( zoneId ).plus( duration ) ;
DateTimeFormatter f = DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.GERMANY) ;
String output = zdt.format( f ) ;
Sonntag, 27. Dezember 2020 um 22:58:52 Nordamerikanische Ostküsten-Normalzeit
java.time
The modern solution uses the java.time classes. Never use Calendar or GregorianCalendar.
UTC
Capture the current moment as seen in UTC. Use Instant.
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
Define a span-of-time unattached to the timeline.
Duration duration = Duration.ofHours( 1 ) ;
Addition.
Instant instantHourLater = instant.plus( duration ) ;
Zoned
You may want to see the time-of-day and date of that moment as seen through the wall-clock time used by the people of a particular region. Apply a time zone (ZoneId) to get a ZonedDateTime object. Same moment, same point on the timeline, different wall-clock time.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( zoneId ) ;
Or, skip the Instant and the Duration.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ).plusHours( 1 ) ;
Text
You said:
I plan to use 24 hours format
The classes such as Instant, OffsetDateTime, and ZonedDateTime represent a moment, a point on the timeline. They have nothing to do with text. They do not have a “format”. They can parse text representing a moment, and they can produce text representing a moment. But internally they have their own way of representing that moment, without any formatted text.
To produce text in a particular format, use DateTimeFormatter class with FormatStyle and Locale. This has been covered many many times already on Stack Overflow. So search to learn more.
DateTimeFormatter f = DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
output: dimanche 27 décembre 2020 à 22 h 51 min 57 s heure normale de l’Est
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?
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Calendar mcalendar = new GregorianCalendar();
The GreogorianCalendar is a subclass of the abstract class Calendar. Therefore what you are doing here is referencing an instance of the GregorianCalendar to the Calendar therefore all the abstract methods in Calendar will follow the implementation of GregorianCalendar
But since your purpose is to add Hours.
You can go ahead with Calendar mcalendar = Calendar.getInstance(); as it retrieves an instance to the current with the the current Locale.
However, if you want to change your Locale, pass in the parameter into the getInstance() method and an instance of the specified Locale will be generated for you.
Refer: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)
And if you want to use Hours:
Do the following:
Do not use HOUR variable as this is only for 12 hour times. Use Calendar.HOUR_Of_DAY to deal with 24 hour timings.

Related

Change the time based on the gmt area on Android

I'm a beginner in android development and I've been searching for hours to find an answer for my question but I didn't really understand anything I found.
The match between 2 teams is starting at 20:00 gmt and I want to make it + - based on the area. For example in germany +1 gmt the time should be 21:00. I only want the hours and minutes format like that.
tl;dr
OffsetDateTime
.of(
LocalDate.of( 2021 , Month.MARCH , 23 ) ,
LocalTime.of( 20 , 0 ) ,
ZoneOffset.UTC
) // Returns a `OffsetDateTime` object.
.atZoneSameInstant(
ZoneId.of( "Europe/Berlin" )
) // Returns a `ZonedDateTime` object.
.toLocalTime() // Returns a `LocalTime` object.
.toString() // Returns a `String` object, with text in standard ISO 8601 format.
21:00
Details
Location does not necessarily correlate to time zone. Users choose their time zone as a preference. Servers should generally be set to UTC (an offset of zero). You can get the JVM’s current default time zone by calling ZoneId.systemDefault. If crucial, you should explicitly ask the user to confirm their desired zone.
I only want the hours and minutes format like that.
Date-time objects are not text, and do not have a "format". Think in terms of the logic needed for handling date-time values rather than in terms of manipulating strings.
starting at 20:00 gmt and I want to make it + - based on the area
Representing that 8 PM in UTC (the new GMT):
LocalDate tomorrow = LocalDate.now( ZoneOffset.UTC ).plusDays( 1 ) ;
LocalTime eightPM = LocalTime.of( 20 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( tomorrow , eightPM , ZoneOffset.UTC ) ;
For example in germany +1 gmt the time should be 21:00
Define your desired time zone.
ZoneId z = ZoneId.of( "Europe/Berlin" ) ;
Adjust from the OffsetDateTime to a ZonedDateTime.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See that code run live at IdeOne.com.
odt.toString(): 2021-02-17T20:00Z
zdt.toString(): 2021-02-17T21:00+01:00[Europe/Berlin]
The odt & zdt objects seen here both refer to the very same simultaneous moment, the same point on the timeline.
This has all been covered many times before on Stack Overflow. Search to learn more.
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?
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It's not Android specific but just a general question about Java.
Use Calendar and SimpleDateFormat like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.set(2021, 1, 16, 20, 00, 00); // 2021-02-16T20:00:00 GMT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
System.out.println(simpleDateFormat.format(calendar.getTime()));
Set (input) your date as GMT. Then format it GMT+01:00 with SimpleDateFormat and print (output) it.

Convert Joda-Time `DateTime` with timezone to DateTime without timezone?

Given a DateTime for example 2015-07-09T05:10:00+02:00 using Joda-Time?
How can I convert it to local time, meaning adding the timezone to the time itself.
Desired output: 2015-07-09T07:10:00
I tried dateTime.toDateTime(DateTimeZone.UTC) but that did not give the desired result.
Adding a bit more info and examples to the correct answers (accepted answer and other one).
UPDATE Added section at end on java.time classes. These supplant Joda-Time.
Purpose of LocalDateTime
You may be confused about the purpose of LocalDateTime.
If trying to represent a date-time value using "wall clock time" as seen by someone in a locality looking at their own clock and calendar, then adjust the time zone of the DateTime object to suit the desired locality.
LocalDateTime is not meant for a particular locality but for the general idea of date+time. For example, "This year's Christmas starts at midnight on December 25, 2014". Conceptually, that is a LocalDateTime, intended to mean different moments in Paris than Montréal and Auckland.
Adjusting Time Zone
Use the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone).
Use proper time zone names. Generally a continent/cityOrRegion.
DateTimeZone zoneParis = DateTimeZone.forID( "Europe/Paris" );
DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTimeZone zoneAuckland = DateTimeZone.forID( "Pacific/Auckland" );
Parse string, assign a time zone, adjust to other time zones.
DateTime dateTimeParis = new DateTime( "2015-07-09T05:10:00+02:00" , zoneParis );
DateTime dateTimeMontréal = dateTimeParis.withZone( zoneMontréal );
DateTime dateTimeAuckland = dateTimeParis.withZone( zoneAuckland );
Dump to console.
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeAuckland: " + dateTimeAuckland );
When run.
dateTimeParis: 2015-07-09T05:10:00.000+02:00
dateTimeMontréal: 2015-07-08T23:10:00.000-04:00
dateTimeAuckland: 2015-07-09T15:10:00.000+12:00
Localize Using Formatted Strings
Joda-Time can translate to a particular locale’s language and customary style when creating a string representation of your date-time object.
DateTimeFormatter formatterMontréal = DateTimeFormat.forStyle( "FF" ).withZone( zoneMontréal ).withLocale( Locale.CANADA_FRENCH );
String outputMontréal = formatterMontréal.print( dateTimeParis );
System.out.println( "outputMontréal: " + outputMontréal );
When run:
outputMontréal: mercredi 8 juillet 2015 23 h 10 EDT
java.time
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. The Joda-Time framework inspired java.time, so concepts are quite similar.
ZoneId and ZoneOffset are the two classes to represent a time zone and offset-from-UTC respectively. An offset is merely a number of hours and minutes and seconds. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZoneId zoneParis = ZoneId.of( "Europe/Paris" );
ZoneId zoneMontreal = ZoneId.of( "America/Montreal" );
ZoneId zoneAuckland = ZoneId.of( "Pacific/Auckland" );
The primary date-time classes in java.time are:
Instant – A moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
OffsetDateTime – An Instant plus a ZoneOffset.
ZonedDateTime – An Instant plus a ZoneId.
The java.time classes use ISO 8601 standard formats by default when parsing/generating strings representing date-time values. So no need to specify a formatting pattern with such inputs.
This input here indicates an offset-from-UTC but not a full time zone. So we parse as an OffsetDateTime rather than a ZonedDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2015-07-09T05:10:00+02:00" );
As the basic building-block of java.time, always in UTC by definition, you may want to extract an Instant.
Instant instant = odt.toInstant(); // `Instant` is always in UTC by definition.
You can adjust into a time zone.
ZonedDateTime zdtParis = odt.atZoneSameInstant( zoneParis );
ZonedDateTime zdtMontreal = odt.atZoneSameInstant( zoneMontreal );
ZonedDateTime zdtAuckland = zdtMontreal.withZoneSameInstant( zoneAuckland );
Localize via the DateTimeFormatter class.
DateTimeFormatter f = DateTimeformatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH );
String output = zdtMontreal.format( f );
See live code in IdeOne.com.
odt: 2015-07-09T05:10+02:00
instant: 2015-07-09T03:10:00Z
zdtParis: 2015-07-09T05:10+02:00[Europe/Paris]
zdtMontreal: 2015-07-08T23:10-04:00[America/Montreal]
zdtAuckland: 2015-07-09T15:10+12:00[Pacific/Auckland]
output: mercredi 8 juillet 2015 23 h 10 EDT
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.
Where to obtain the java.time classes?
Java SE 8 and 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.
What #Nazgul said is right, but in case all you want to achieve is a "wall-time" in UTC zone you can do something like that:
DateTime dateTimePlus2 = DateTime.parse("2015-07-09T05:10:00+02:00");
System.out.println(dateTimePlus2);
DateTime dateTimeUTC = dateTimePlus2.withZone(DateTimeZone.UTC);
System.out.println(dateTimeUTC);
LocalDateTime localDateTimeUTC = dateTimeUTC.toLocalDateTime();
System.out.println(localDateTimeUTC);
Result:
2015-07-09T05:10:00.000+02:00
2015-07-09T03:10:00.000Z ("Z" == Zulu tz == UTC)
2015-07-09T03:10:00.000
As you can see, the time is not "07:10" as you expected, because UTC+2 zone is two hours ahead of UTC. Converting to UTC subtracts 2 hours.
DateTime without timezone dosnt make sense. DateTime are always relative to the timezone in which they are used. Without the timezone information a date time combination makes no sense for the geography as such. raw timestamp millies can however be accessed as the number of millies gone since 1st Jan 1970 but any concrete date time combinations must have a timezone with it.

Gregorian Calendar and date before 1970

How can i fix the variable "time" for the gregorian calendar date before 1970. Or what was the unit of the variable "time" of gregorian calendar for the date before 1970?
I use hibernate for the object-relational mapping. And the data I'm trying to Save to my database is a date type gregorian calendar. But whenever the date is less than 1970, my application crash.
Timestamps before Epoch (1970 Jan 1st) are represented by negative numbers. Have a look at this SO answer to see an example.
If your application "crashes" (whatever that means), you need to look how is it represented in the database and how is it mapped.
tl;dr
ZonedDateTime.of(
LocalDate.of( 1969 , Month.DECEMEBER , 25 ) ,
LocalTime.NOON ,
ZoneId.of( "Africa/Tunis" )
).toInstant()
Crash?
You have not presented enough information to diagnose your crash.
Beware that the date-time capabilities of various databases varies widely. The SQL standard barely touches on the topic of date-time handling, so little is required. Some databases have quite limited support. Any serious enterprise-oriented database should be able to easily store moments going many centuries both in the past as well as the future.
java.time
Use the java.time classes added to Java 8 and later. These types are apparently now supported in Hibernate (I’m not a user).
Internally, moments after the epoch of 1970-01-01T00:00Z (first moment of 1970 in UTC) are represented as a count of nanoseconds, a positive number. For moment before the epoch, a negative number of nanoseconds. But you should not really care. Just use the java.time classes as intended, and never see that count number.
If you were to want noon of Christmas Day in 1969 in New Zealand:
LocalTime lt = LocalTime.NOON ;
LocalDate ld = LocalDate.of( 1969 , Month.DECEMEBER , 25 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Database
With JDBC 4.2 and later, you can directly exchange these java.time types with your database. No need for numbers or strings. The old java.sql.Timestamp and related classes are now legacy, and can be forgotten.
Adjust your moment from its time zone to UTC, extract a Instant. Same simultaneous moment, same point on the timeline, but viewed through the lens of the wall-clock time used by the people of a particular region.
Instant instant = zdt.toInstant() ;
Pass to your database for a column of type TIMESTAMP WITH TIME ZONE.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( ZoneId.of( "America/Montreal" ) ) ;
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.
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.
Cant you use Calender class?
public class DatePrint {
public static void main(String[] argv) {
Calendar c = new GregorianCalendar(1900, 10, 11);
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " "
+ c.get(Calendar.MONTH) + ", " + c.get(Calendar.YEAR) + " "
+ c.get(Calendar.ERA));
}
}

Show ISO-8601 date+time in current time?

for example, 2012-10-30T22:30:00+0300 need to be shown in 2012-10-30T22:30:00-0600 (the local time for example)
need to implement in java (android app)
how can I manage doing that?
That's what a Date is: a universal instant in time. Choose the appropriate time zone when displaying it, and you'll have the time string you want:
Date now = new Date();
DateFormat df = df.getDateTimeInstance();
System.out.println(df.format(now)); // now, displayed in the current time zone (examle: Germany)
df.setTimeZone(theLondonTimeZone);
System.out.println(df.format(now)); // now, displayed in the time zone of London
tl;dr
OffsetDateTime
.parse(
"2012-10-30T22:30:00+0300" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" )
)
.toInstant()
.atZone(
ZoneId.of( "Europe/London" )
)
.toString()
2012-10-30T19:30Z[Europe/London]
java.time
The modern solution uses the java.time classes.
Define a formatter to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" ) ;
Parse the input as a OffsetDateTime.
String input = "2012-11-05T13:00:00+0200" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-11-05T13:00+02:00
Tip: Always include the COLON character as a delimiter between the hours and minutes of the offset. We could then skip the custom formatting pattern: OffsetDateTime.parse( "2012-11-05T13:00+02:00" ).
Adjust to UTC, an offset of zero hours-minutes-seconds, by extracting a Instant object.
Instant instant = odt.toInstant() ;
In standard ISO 8601 format, the Z on the end means UTC (offset of zero). Pronounced “Zulu”.
instant.toString(): 2012-11-05T11:00:00Z
Adjust into London time.
ZoneId zLondon = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdtLondon = instant.atZone( zLondon ) ;
zdtLondon.toString(): 2012-11-05T11:00Z[Europe/London]
Adjust to another time zone.
ZoneId zMontreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtMontreal = instant.atZone( zMontreal );
zdtMontreal.toString(): 2012-11-05T06:00-05:00[America/Montreal]
All these objects (odt, instant, zdtLondon, and zdtMontreal) represent the very same simultaneous moment, the same point on the timeline. Same moment, different wall-clock 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.
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?
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….
https://i.stack.imgur.com/eKgbN.png
Table of which java.time library to use with which version of Java or Android
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.
Using joda time library solved my problem optimally, using dateTime & dateTime zone like following:
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
DateTime dt = new DateTime();
DateTime dt2 = new DateTime();
dt = DateTime.parse("2012-11-05T13:00:00+0200");
System.out.println(dt.toString());
dt2 = DateTime.parse("2012-11-05T21:45:00-08:00");
DateTimeZone dtz = dt2.getZone();
System.out.println(dt.withZone(dtz).toString());

How to include milliseconds in a formatted date string?

Hi I am coding the following:
String sph=(String) android.text.format.DateFormat.format("yyyy-MM-dd_hh-mm-ss_SSS", new java.util.Date());
I want the current date and time and milliseconds
what it gives me is:
2011-09-01_09-55-03-SSS
The SSS is not converting back to milliseconds...
Does anyone know why and what should it be to get the milliseconds in 3 position?
Thanks
Use the following:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
String dateString = formatter.format(new java.util.Date());
tl;dr
ZonedDateTime // Represent a moment in the wall-clock time used by the people of a certain region (a time zone).
.now() // Capture current moment. Better to pass optional argument for `ZoneId` (time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` with text in a custom formatting pattern.
DateTimeFormatter.ofPattern( "uuuu-MM-dd_HH-mm-ss-SSS" )
) // Returns a `String` object.
2018-08-26_15-43-24-895
Instant
You are using troublesome old legacy date-time classes. Instead use the java.time classes.
If you want the date-time in UTC, use the Instant class. This class holds nanosecond resolution, more than enough for milliseconds.
Instant instant = Instant.now();
String output = instant.toString();
That toString method uses the DateTimeFormatter.ISO_INSTANT formatter which prints 0, 3, 6, or 9 digits in the decimal fraction, as many as needed appropriate to the actual data value.
In Java 8 the current moment is captured only up to milliseconds but a new implementation of Clock in Java 9 may capture up to nanoseconds. So truncate to milliseconds if that is your requirement. Specify your desired truncation by a TemporalUnit as implemented in ChronoUnit.MILLIS.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS );
ZonedDateTime
If you want a specify time zone, apply a ZoneId to get a ZonedDateTime.
Instant instant = Instant.now();
instant.toString(): 2018-08-26T19:43:24.895621Z
Instant instantTruncated = instant.truncatedTo( ChronoUnit.MILLIS );
instantTruncated.toString(): 2018-08-26T19:43:24.895Z
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
String output = zdt.toString();
2018-08-26T15:43:24.895621-04:00[America/Montreal]
Again if you want other formats, search Stack Overflow for DateTimeFormatter.
DateTimeFormatter
If you want to force three digits for milliseconds, even if the value is all zeros, specify a custom formatting pattern using DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd_HH-mm-ss-SSS" ) ;
String output = zdt.format( f ) ;
2018-08-26_15-43-24-895
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, 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
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….
Try using the same format with SimpleDateFormat

Categories