Java: Date from unix timestamp

后端 未结 10 1742
北荒
北荒 2020-11-22 04:10

I need to convert a unix timestamp to a date object.
I tried this:

java.util.Date time = new java.util.Date(timeStamp);

Timestamp value

10条回答
  •  面向向阳花
    2020-11-22 04:35

    Looks like Calendar is the new way to go:

    Calendar mydate = Calendar.getInstance();
    mydate.setTimeInMillis(timestamp*1000);
    out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
    

    The last line is just an example how to use it, this one would print eg "14.06.2012".

    If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.

    If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).

    https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

提交回复
热议问题