1

I did some searched on web about BigInt data conversion into date while I've found plenty of same question but non of them seems to work. There is 13 digit's data 1435555326831 into my database and I think this is UNIXTIME, now I want to convert it into yyyy-MM-dd HH:mm:ss form. Thank you

Dhiren Hamal
  • 874
  • 1
  • 12
  • 31
  • Which version of Java? The answer differs depending on whether you use Java 8 or another, lower version – fge Jun 29 '15 at 09:17
  • 1
    Didn't `new Date(BigInt.longValue());` work??? – Codebender Jun 29 '15 at 09:24
  • 1
    FYI, classic [Unix Time](https://en.m.wikipedia.org/wiki/Unix_time) is a count of *whole* seconds since first moment of 1970 in UTC time zone while ignoring [Leap Seconds](https://en.m.wikipedia.org/wiki/Leap_second). What you have is apparently *milliseconds*. Also, be aware of other granularities. Some systems use *microseconds*, especially databases such as Postgres. The new java.time package built into Java 8 and later uses *nanoseconds*. – Basil Bourque Jun 29 '15 at 18:25

2 Answers2

6

You can first convert the number into a long (if you receive a BigInteger, you can call BigInteger.longValue()).

Then you have two options. With the standard java.util.Date you can use:

long millis = 1435555326831L;
Date d = new Date(millis);

You can then format the date with a SimpleDateFormat for output.

If you can use Java 8's new Time API, you can create an instant and convert it to the desired time zone (your computer time zone in my example below):

Instant instant = Instant.ofEpochMilli(millis);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(fmt.format(instant.atZone(ZoneId.systemDefault())));

Note that these conversions only work if BigInteger is smaller than the maximum long size, not in general. This shouldn't be an issue, since the maximum value of a long is 2^63 - 1, but if your BigInteger is user input, you need to check for this.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
0

Your data is on Unix timestamp and you can simply convert it by using new java.util.Date() and here is the example of it Java: Date from unix timestamp

Community
  • 1
  • 1