Pavan
Pavan

Reputation: 77

getting Out of Range Compile Time Error in the Date Constructor

I am getting a date value as 1598331600000 from a API call

I am trying to convert this to Readable format using SimpleDateFormat

But i am getting Out of Range Compile Time Error in the Date Constructor

This is my Program

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Calendar cal = Calendar.getInstance();

        Date date = new java.sql.Date(1598331600000);
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");

        String formattedDate = sdf.format(date);

        System.out.println(formattedDate);

    }

}

Could you please let me know how to resolve this error .

Upvotes: 0

Views: 329

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 40078

I would recommend to use java-8 date time api, and stop using legacy Calendar, SimpleDateFormat

Instant.ofEpochMilli(1598331600000l)
       .atZone(ZoneId.systemDefault())
       .format(DateTimeFormatter.ofPattern("MMddyyyy")) //08252020

Upvotes: 2

Som
Som

Reputation: 1610

Your value here is treated as integer.

Date date = new java.sql.Date(1598331600000);

The constructor can take Long values. Like this :

long millis=System.currentTimeMillis();
Date date = new java.sql.Date(millis);

Hence it is throwing the error.

Try out this code :

import java.util.*;
import java.text.SimpleDateFormat;


public class Main{
    public static void main(String[] args) {
        
        Calendar cal = Calendar.getInstance();
        /*long millis=System.currentTimeMillis();  <---- This also works
        Date date = new java.sql.Date(millis);*/
        Date date = new java.sql.Date(1598331600000L);  // <---Look the L for Long here
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate);
    }
}

Output :

08252020

Upvotes: 0

Andrew Vershinin
Andrew Vershinin

Reputation: 1968

1598331600000 without a suffix is treated as an int, and this value is too big for it (int can hold values up to around 2 billion, 2^31 - 1). Use L suffix for long type, which can hold values up to 2^63 - 1: 1598331600000L.

Upvotes: 3

Related Questions