Preface
No matter what programming language it is, no matter how long it has been to learn or how long it has been, it is inseparable from the conversion of timestamps and time. The same is true in Java. Now the lowest Java version is Java 8.
Get the timestamp
//Use system time stamplong timestamp = (); ("timestamp:" + timestamp); //>>timestamp:1733907943319 Long timestamp1 = ().toEpochMilli(); ("timestamp1:"+timestamp1); //>>1733908000856 //Get the second time stamplong timestamp2 = () / 1000; ("timestamp2:"+timestamp2); //>>1733908113 long timestamp3 = ().getEpochSecond(); ("timestamp3:"+timestamp3); //>>1733908113
Date time object to time stamp
LocalDateTime localDateTime = (); ("localDateTime:"+localDateTime); //>>localDateTime:2024-12-11T17:10:45.800 //Get our common time formatString dateTime = (("yyyy-MM-dd HH:mm:ss")); ("dateTime:"+dateTime); //>>dateTime:2023-04-07 14:06:53 //localDateTime gets the timestamplong timestamp4 = (("+8")).toEpochMilli(); ("timestamp4:"+timestamp4); //>>1733908245800 long timestamp5 = (()).toInstant().toEpochMilli(); ("timestamp5:"+timestamp5); //>> 1733908324740 long timestamp6 = ().toInstant().toEpochMilli(); ("timestamp6:"+timestamp6); //>>1733908374866 long timestamp7 = ().toEpochSecond(); ("timestamp7:"+timestamp7); //>>1733908374 long timestamp8 = ().toLocalDateTime().toEpochSecond(("+8")); ("timestamp8:"+timestamp8);
Time stamp to time object
long time = (); DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss"); ("time:"+time); // Convert millisecond timestamps to Instant objectInstant instant=(time); ("instant:"+instant); // Convert the Instant object to the LocalDateTime object, use the system default time zoneLocalDateTime localDateTime=(instant, ()); ("localDateTime:"+(formatter)); LocalDateTime localDateTime1 =((),0, ("+8")); ("localDateTime1:"+(formatter));
Get the time object through the time string
String dt = "2024-12-11"; String dtt = "2024-12-11 17:44:28"; String format_DateTime = "yyyy-MM-dd HH:mm:ss"; DateTimeFormatter df = (format_DateTime); LocalDateTime localDateTime = (dtt, df); ("localDateTime:"+localDateTime); //Convert to InstantInstant instant = (("+8")); ("instant:"+instant); ("Millisecond time stamp:"+()); ("Second Timestamp:"+()); LocalDate localDate = (dt); ("localDate:"+localDate); ("():"+().format(df)); //Convert to InstantInstant instant1 = ().toInstant(("+8")); ("Millisecond time stamp:"+()); ("Second Timestamp:"+());
The above is to get the timestamp in Java 8, get the timestamp through the practice object and get the time object through the timestamp.
Summarize
This is the end of this article about the conversion method of timestamps and time in Java. For more related contents of timestamps and time conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!