Java Timestamp belongs to the thin wrapper of java.util.Date and allows it to be recognized as a SQL TIMESTAMP type value by the JDBC API. Timestamp supports operations like formatting and parsing to help escape the syntax of JDBC for timestamp values.
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
The precision of this Java timestamp is known to be either:
- 19, which is the total number of characters in the format yyyy-mm-dd hh:mm:ss.
- 20 + s precision which is the total number of characters in the format yyyy-mm-dd hh:mm:ss, where s indicates the scale of the given timestamp, which is the fractional seconds precision.
Note: Timestamp belongs to the composite of type java.util.Date and having a separate nanosecond value. The stored values are of integral seconds in java.util.Date component. The Nanos, which are separate, belong to fractional seconds. The method Timestamp.equals(Object) does not return true when an object is passed, which does not belong to an instance of java.sql.Timestamp. This is because the Nanos component is unknown to that date. This leads to asymmetry of Timestamp.equals(Object) method as compared to java.util.Date.equals(Object) method. The underlying java.util.Date implementation will be used by the hashcode method, and hence Nanos will not be included in the computation.
Syntax:
Timestamp(long time)
Using a milliseconds time value, it constructs a timestamp value.
Methods of Java Timestamp
Working of timestamp function in Java: timestamp can be used in a lot of methods, and a few of them are explained in detail below-
1. after
Shows if the present Timestamp object is later than the given object.
public boolean after(Timestamp tm)
Where tm is the value of Timestamp, which we compare with this Timestamp object, this function returns a boolean value; true if this Timestamp value is later and vice versa.
2. before
Shows if the present Timestamp object comes before to the given object.
public boolean before(Timestamp tm)
Where tm is the value of Timestamp which we compare the Timestamp object with this function returns a boolean value; true if this Timestamp value is before and vice versa.
3. compareTo
This is a comparison function that compares the given Timestamp object with this one.
public int compareTo(Timestamp tm)
Where tm is the object which is to be compared with this Timestamp object, this function returns 0 value when both the objects are equal; any value less than 0 when this object comes before the given object and a value bigger than 0 when Timestamp object is after the given Timestamp object.
4. equals
Using this function, we can check if the two given Timestamp objects are equal or not.
public boolean equals(Timestamp tm)
Where tm refers to the Timestamp value, we have to compare it with this Timestamp object. This function returns boolean values; true is returned if the values are equal and false if not.
5. getTime
This function gives the total number of milliseconds starting from the default date value Jan 1, 1970, 00:00:00 GMT, which is indicated by this Timestamp object.
public long getTime()
This function will override the function of getTime of class Date if present. It returns the number of milliseconds from the default date as shown above.
6. getNanos
This function is used to fetch this Timestamp object’s value in Nanos.
public int getNanos()
This function returns the object’s fractional second parameter.
7. toInstant
This is used to change a Timestamp object to an Instant. During this conversion, an Instant is created, which indicates the point on the line, which is the same as this Timestamp.
public Instant toInstant()
This function overrides the toInstant method of class Date. It returns an instant that represents the same point on the line of time-line.
8. setTime
This function sets a Timestamp object to indicate a time in milliseconds which is after Jan 1, 1970, 00:00:00 GMT.
public void setTime(long time)
This function overrides the method setTime in class Date. It takes the input parameter time, which is the number of milliseconds.
9. getTime
This function is used to get the time in a number of milliseconds since Jan 1, 1970, 00:00:00 GMT, which this Timestamp object represents.
public long getTime()
This function returns the time in milliseconds since the default time mentioned above.
10. valueOf
This method converts the String object belonging to the JDBC timestamp escape format to the Timestamp value type.
public static Timestamp valueOf(String str)
An str parameter is the timestamp of format yyyy-[m]m-[d]d hh:mm:ss and the fractional seconds can be ignored. The leading zero given for mm and dd can also be ignored. This function returns its respective Timestamp value. And throws an IllegalArgumentException when the parameter is given is not of the mentioned format.
Examples to Implement Java Timestamp
Below are the examples of Java Timestamp:
Example #1
Code:
// Java program to demonstrate the // functionalit of getTime() function import java.sql.*; class Demo { public static void main(String args[]) { // Here we are creating 2 timestamp objects Timestamp tm = new Timestamp(2000); // Displaying the created timestamp object System.out.println("The Timestamp time is : " + tm.toString()); System.out.println("The Time in milliseconds is : " + tm.getTime()); } }
Output:
In the above example, we are first creating a timestamp object. Then we are printing out using two different functions toString and getTime to check the output.
Example #2
Code:
// Below Java code is to showcase the // functionality of getTime() function import java.sql.*; public class Example { public static void main(String args[]) { // Creating 2 timestamp objects Timestamp tm = new Timestamp(-2000); // Display the timestamp object System.out.println("Timestamp time is : " + tm.toString()); System.out.println("Total time in milliseconds : " + tm.getTime()); } }
Output:
In the above example, we are first creating 2 timestamp objects and using the getTime() function to fetch the timestamp object’s time and initialize it to a time before the default time of Jan 1 1970. Hence the negative long value given does the purpose.
Advantages of using Timestamp in Java
- We can notice a clear separation with the Timestamp object’s help between two different time duration, especially Instant and Duration or fragment-related definitions. Ex LocalDate, LocalTime.
- In comparison with java.Util.The date this Timestamp object allows a better set of functions for manipulating and calculating the logic.
- It also covers the conversion of units with the help of Duration.toDays().
- It also covers the Timezone hell with the help of ZonedDateTime.
Conclusion
As seen above, the Timestamp is an extension of java.util.Date class is used as a wrapper to that class in JDBC API to maintain specific SQL requirements. It is mostly used when working with databases and gives output in nanoseconds precision.
The above is the detailed content of Java Timestamp. For more information, please follow other related articles on the PHP Chinese website!

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
