8

I made this snippet to show my problem:

import java.text.SimpleDateFormat;

public class Foo {
    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy");
        String date1 = "1412293500";
        String date2 = "1412336700";
        String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
        String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
        System.out.println(dateString1 + " " + dateString2);

    }
}

date1 and date2 are expressed in seconds, so I'm expecting two different dates in output, but the dates are printed the same. I checked inside this online tool, and as you can see the dates are related to two different days.

How can I solve this?

OiRc
  • 1,602
  • 4
  • 21
  • 60
  • First, post code that compiles. – hd1 Sep 07 '15 at 13:09
  • First, your code is wrong because you wrote dat2 in the var declaration. Anyway it's true im my jwm prints out date1: 45 01 03 10 2014 date2: 45 01 03 10 2014 probably it rounds at a certain value – Yuri Blanc Sep 07 '15 at 13:11

2 Answers2

8

The difference between your two timestamps is exactly 12 hours.

The h identifier in SimpleDateFormat formats the hours in AM/PM (1-12), so you actually do not output the real difference: the date was shifted from AM to PM.

Try with the k or H identifier which formats the hour in day as (1-24) or (0-23).

SimpleDateFormat formatter = new SimpleDateFormat("mm kk dd MM yyyy");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 45 13 03 10 2014

You could also output the AM/PM marker with the a identifier like this:

SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy aa");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 AM 45 01 03 10 2014 PM
Tunaki
  • 132,869
  • 46
  • 340
  • 423
4

This is because your dates are 12h appart and you use the lower case 'h' for the hour formatting. The dates are 1am and 1pm, respectively. In order to see this in your output use upper case 'H' or add 'a' to the format for the 'am/pm' marker.

Bernhard
  • 8,583
  • 4
  • 41
  • 42