Search code examples
javadatetimelocale

I have a big integer value which I need to convert into date time in (yyyy-mm-dd hr:ss:mss)


I have a big integer value which I need to convert into date time in (yyyy-mm-dd hr:ss:mss)

BigInteger sum= new BigInteger("2023062223380346");
    //  long unixSeconds = 1429582984839;
           Date date1 = new Date(sum); 
           SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a"); 
           sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
           String formattedDate = sdf.format(date1);
            System.out.println(formattedDate);

Expected output- 2023-06-22 23:38:03:466


Solution

  • tl;dr

    LocalDateTime
    .parse( 
        "20230622233803466" , 
        DateTimeFormatter.ofPattern ( "uuuuMMddHHmmssSSS" ) 
    )
    .toString()
    .replace( "T" , " " )
    

    2023-06-22 23:38:03.466

    Details

    You are using terrible legacy date-time classes were years ago supplanted by the modern java.time classes defined in JSR 310. Always use java.time classes for your date-time handling.

    java.time classes

    I assume your example input string "2023062223380346" is a typo, as it is missing a digit on the end when compared to your desired output 2023-06-22 23:38:03:466.

    Define a formatting pattern to match your input.

    String input = "20230622233803466";
    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuuMMddHHmmssSSS" );
    

    Parse as a LocalDateTime, a date with time of day but lacking the context of a time zone or offset-from-UTC.

    LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
    

    Generate text in standard ISO 8601 format.

    String iso8601 = ldt.toString() ; 
    

    Replace the T in the middle with a SPACE, per your desired output.

    String output = iso8601.replace( "T" , " " ) ;
    

    See this code run at Ideone.com.

    iso8601 = 2023-06-22T23:38:03.466

    output = 2023-06-22 23:38:03.466

    Apparently you want to interpret this as representing a moment in a specific time zone. Use time zone names rather than assuming an offset. Offsets can vary for different periods of time — that is the definition of a time zone, a named history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians.

    ZoneId z = ZoneId.of( "Europe/London" ) ;
    ZonedDateTime zdt = ldt.atZone( z ) ;
    

    zdt.toString() = 2023-06-22T23:38:03.466+01:00[Europe/London]


    Tip: Educate the publisher of your data about the benefits of using standard ISO 8601 formats when communicating date-time values textually.