-1

when I run the following code:

package testframe;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class dates {

    public static void handleLastValueDate()  {

        Timestamp stamp = new Timestamp(1490018838);
        Date date = new Date(stamp.getTime());
         SimpleDateFormat df =  new SimpleDateFormat("yyyy-MM-dd HH:mm");

    }

    public static void main(String[] args) {

        handleLastValueDate();

    }

}

I get the following result: 1970-01-18 07:53 which is incorrect and should be

GMT: Mon, 20 Mar 2017 12:55:38 GMT
Your time zone: 3/20/2017, 2:55:38 PM GMT+2:00

can anyone please explain for me why this is happening? I tired to play with locale but also that didn't help! how can I see the correct time?

thanks.

5
  • 1
    You never use DateFormat in your code. How it can be wrong? Commented Mar 20, 2017 at 14:15
  • the expected result is a completely different format as to what you specified in the simpledateFormat ? Commented Mar 20, 2017 at 14:15
  • I don't see a print statement anywhere. Commented Mar 20, 2017 at 14:15
  • Q: what does that line do? 'SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");' A: it sets the format you are getting which is the format used in 1970-01-18 07:53... Commented Mar 20, 2017 at 14:17
  • You're missing 3 digits from the long representation of your date. Commented Mar 20, 2017 at 14:20

1 Answer 1

2

Your code is printing 1970-01-18 07:53 because you need to multiply 1490018838 by 1000 (milliseconds), on the other hand, no need to use the TimeStamp, Date class has an overloaded Constructor taking the epoch in milliseconds

Date date = new Date(1490019439L * 1000);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(df.format(date));

be awware also about this.

new Date(1490019439L * 1000)

am using the timeStamp as Long literal, if you dont, then an overflow in the integer will happens and you will get again a wrong date...

Sign up to request clarification or add additional context in comments.

2 Comments

can I use the timestamp given as input to format method?
and thanks for your quick answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.