1

If I am running unix command

echo 1378223625 | xargs -L 1 -I '{}' date -d "@{}" "+%d-%m-%Y-%H-%M %Z"

result is 03-09-2013-17-53 CEST

If I am running from java

public class DateExperiment {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy-H-m z");
        System.out.println(df.format(1378223625) );
    }
}

my result is 16-01-1970-23-50 CET

unix command gives correct result but java is giving me wrong result.

Can anybody explain why am getting this discrepancy? what is the mistake?

2
  • 2
    but java is giving me wrong result. No, your expectations are wrong. Commented Jun 23, 2014 at 2:57
  • 1
    Another good example of why one should not use a count-since-epoch to handle date-time values. Commented Jun 23, 2014 at 5:59

2 Answers 2

3

If you use a numerical value as an argument to SimpleDateFormat#format(..), it uses the Date constructor which expects a long. That constructor

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

The value you provided represents

16-01-1970-23-50 CET

The problem here is that you have seconds, not milliseconds.

You'll want

System.out.println(df.format(1378223625000L));
Sign up to request clarification or add additional context in comments.

Comments

2

Unix is giving you the time in seconds since epoch, Java is expecting milliseconds. I get your expected output if I multiply by 1000.

System.out.println(df.format(1378223625*1000L));

Outputs

03-09-2013-11-53 EDT

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.