Java convert millisecond timestamp to date


In Java, you can convert a millisecond timestamp to a Date object with respect to a given timezone using the SimpleDateFormat and TimeZone classes.

Example code:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimestampConverter {
    public static void main(String[] args) {
        long timestamp = 1651462625000L; // example timestamp in milliseconds
        TimeZone timezone = TimeZone.getTimeZone("America/New_York"); // example timezone
        
        Date date = new Date(timestamp);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(timezone);
        String formattedDate = formatter.format(date);
        System.out.println(formattedDate);
    }
}

In this example, we have a millisecond timestamp and a timezone that we want to use to convert the timestamp to a date. We create a Date object using the timestamp, and a TimeZone object using the given timezone.

Next, we create a SimpleDateFormat object that specifies the format we want to use for the date (yyyy-MM-dd HH:mm:ss), and we set its timezone to the one we created earlier using the setTimeZone() method.

We then use the formatter object to format the date as a string in the desired format with respect to the given timezone.

Finally, we print the formatted date to the console. The output will be a string representing the date and time of the given timestamp in the format yyyy-MM-dd HH:mm:ss with respect to the given timezone.

Thanks for Learning….