Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

422
Visualizações
convert exp date JWT token in java not work like in js, why?

I'm trying to get value of the exp datetime in a JWT token. exp is the expiration time after which JWT must not be accepted.

In JavaScript I get the correct result by

new Date(1661159784*1000) 

the correct result is

Mon Aug 22 2022 11:16:24 GMT+0200 (CEST)

Why didn't I get the same in Java?

Java:

System.out.println(new Date(1661159784 * 1000)); 

result:

Sat Dec 20 13:17:20 CET 1969

The same result setting s UTC time zone:

final ZonedDateTime exp2 = Instant.ofEpochMilli(1661159784 * 1000)
                                  .atZone(ZoneOffset.UTC);
System.out.println(exp2);

result:

1969-12-20T12:17:20.448Z
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The constructor of Date you used takes a long argument, but what you passed is in fact an (overflown) int:

public static void main(String[] args) {
    int overflowedInt = 1661159784 * 1000;
    System.out.println(overflowedInt);
}

Output: -992559552

The same applies to Instant.ofEpochMilli(long)…


You can get the desired result if you use Instant.ofEpochSecond(long) without multiplying by 1000:

public static void main(String[] args) {
    Instant instant = Instant.ofEpochSecond(1661159784L);
    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
    System.out.println(zdt);
}

Output:

2022-08-22T09:16:24Z[UTC]

If you have to use a java.util.Date, which is not recommended anymore, either do the calculation with longs:

System.out.println(new Date(1661159784L * 1000L));

or — much better — use the compatibility method Date.from(Instant) and create the Instant as shown at the top of this answer, that is Instant.ofEpochSecond(long):

System.out.println(Date.from(Instant.ofEpochSecond(1661159784L)));

Output:

Mon Aug 22 11:16:24 CEST 2022

… in my TimeZone/ZoneId ("Europe/Berlin"), pay attention to the zones here.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda