Home > Article > Backend Development > How to convert PHP timestamp to Java timestamp
If you need to convert a timestamp in PHP to a timestamp in Java, you need to understand how time is represented between the two languages. In PHP, a timestamp is an integer representing the number of seconds between the Unix epoch (January 1, 1970 00:00:00 UTC) and the current time. In Java, a timestamp is a long integer, representing the number of milliseconds from January 1, 1970, 00:00:00 UTC, to a certain time. Therefore, you need to do some appropriate conversions to convert PHP timestamps to Java timestamps.
The following is a simple PHP function that converts a known timestamp into a timestamp that Java can accept:
function phpToJavaTimestamp($phpTimestamp) { return (int) ($phpTimestamp / 1000); }
This function simply divides the PHP timestamp by 1000, The result is then converted to an integer, which converts seconds to milliseconds. You can then pass the PHP timestamp as a parameter to this function and use the return value in Java.
In Java, you can use Date and SimpleDateFormat classes to handle dates and times. Below is a simple Java class that converts a known PHP timestamp to a Java timestamp:
import java.util.Date; import java.text.SimpleDateFormat; public class TimestampConverter { public static long phpToJavaTimestamp(int phpTimestamp) { long javaTimestamp = ((long) phpTimestamp) * 1000; return javaTimestamp; } public static void main(String[] args) { int phpTimestamp = 1634395081; long javaTimestamp = phpToJavaTimestamp(phpTimestamp); Date date = new Date(javaTimestamp); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = dateFormat.format(date); System.out.println(dateString); } }
In this class, we define a static method phpToJavaTimestamp() that converts a PHP timestamp Convert to Java timestamp. In the main() method, we use this method to convert the PHP timestamp to a Java timestamp and pass it to the constructor of the Date class. We then use the SimpleDateFormat class to format the date and time into a string and output the result.
You can modify this code as needed to suit your specific needs. Additionally, you can use other date and time processing classes, such as the Calendar and DateTimeFormatter classes. Whatever method you choose, just remember that proper timestamp conversion can help you pass date and time variables efficiently between different programming languages.
The above is the detailed content of How to convert PHP timestamp to Java timestamp. For more information, please follow other related articles on the PHP Chinese website!