search
HomeJavajavaTutorialJava Timestamp

Java Timestamp

Aug 30, 2024 pm 03:39 PM
java

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 Tests

Start 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:

Java Timestamp

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:

Java Timestamp

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

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

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

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.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

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

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

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

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

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.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

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

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

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

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MinGW - Minimalist GNU for Windows

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

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

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools