Understanding Timestamps: In Java, a timestamp is a long integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 GMT. This is known as the Unix Epoch time. It's important to understand this format as it's used in many Java applications.
Converting Timestamps to Dates: To convert a timestamp to a date object in Java, you can use the SimpleDateFormat class. This class allows you to specify the format of the date and time values. For example, to convert a timestamp to a date object in the format "dd/MM/yyyy", you can use the following code:
1 2 3 4long timestamp = 1615225817878L; Date date = new Date(timestamp); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String formattedDate = formatter.format(date); System.out.println(formattedDate);
This will output: "08/03/2021".
Converting Dates to Timestamps: To convert a date object to a timestamp in Java, you can use the getTime() method of the Date class. This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. For example
1 2 3 4String dateString = "08/03/2021"; SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Date date = formatter.parse(dateString); long timestamp = date.getTime(); System.out.println(timestamp);
This will output: "1615190400000".
Handling Timezones: When working with timestamps in Java, it's important to consider timezones. By default, Java uses the system's timezone, but you can specify a specific timezone using the TimeZone class. For example, to use the timezone "America/Los_Angeles", you can use the following code: