Skip to content
Advertisement

Issue with HH date time format

Need help to identify where is the issue, whether it is a java issue or linux box or something else.

My app is running on linux weblogic, app is generating some kind of .tar files on linux with datetimestamp in filename.

I am using below snippet to get current time to prepare filename:

String dateTimeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(Calendar.getInstance().getTime());

File format: SA_PART_YYYYMMDD-HHMMSS_sequence.tar

below are files from linux box: if you observe carefully, HH (hour) part is switching between 13 to 12 to 13 to 12 to 14 to 13. and there is no major differnce between minutes and seconds.

I need to understand why HH is printing wrong here?

-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:45 SA_PART_20180412-134347_6000010739.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:45 SA_PART_20180412-134351_6000010740.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:45 SA_PART_20180412-124355_6000010741.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:45 SA_PART_20180412-124357_6000010742.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:47 SA_PART_20180412-134523_6000010743.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:47 SA_PART_20180412-134526_6000010744.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:47 SA_PART_20180412-124531_6000010745.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 17:47 SA_PART_20180412-124531_6000010746.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 18:17 SA_PART_20180412-141524_6000010747.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 18:17 SA_PART_20180412-141528_6000010748.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 18:17 SA_PART_20180412-131531_6000010749.tar
-rw-rw-rw- 1 med1 temp1 20480 Apr 12 18:17 SA_PART_20180412-131533_6000010750.tar

Advertisement

Answer

It’s very likely to be a time zone issue. new SimpleDateFormat("yyyyMMdd-HHmmss") creates a SimpleDateFormat that uses the JVM’s time zone setting. This setting can be changed at any time from other parts of your program and from other programs running in the same JVM. So it’s fragile. Say, for example, that two different parts of your program need to set the setting and set it differently. This would explain.

The solution is to give an explicit time zone. The modern way:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
        String dateTimeStamp = LocalDateTime.now(ZoneId.of("Pacific/Norfolk")).format(formatter);

Or if you don’t want to leave the long outdated and notoriously troublesome SimpleDateFormat class just yet:

        DateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss");
        format.setTimeZone(TimeZone.getTimeZone("Pacific/Norfolk"));
        String dateTimeStamp = format.format(System.currentTimeMillis());

Both of the above snippets give the same result, like 20180413-190318. In either case, please fill in your desired time zone where I put Pacific/Norfolk.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement