×

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is used. This class is similar to the java.sql.Date and it is used only when working with databases in java.

  • Formatting and parsing operations are added for supporting the JDBC escape syntax for time values.

Class Hierarchy

java.lang.Object
   |
   +----java.util.Date
           |
           +----java.sql.Time

All implemented interfaces:

Serializable, Cloneable, Comparable<Date>

In the SQL package, the time class is used to display the time valuejava.sql.Time we can display time without a date. Whereas java.sql.date is used for displaying date,without time. For both date and time, we use java.sql.Timestamp. Here java.sql.Date and java.sql.Time is the subclass of java.util.Date. java.sql.Date and java.sql.Time both inherit from java.util.Date.

  • The time value is initially set to 1st January 1970. The time value after that is positive and the time value before that is negative.

Constructor and Methods in java.sql.Time

Here are some of the constructors and methods in java.sql.Time class.

1. java.sql.Time Constructors:

  • Time(int,int,int) – Used for Constructing a Time Object. 
    public Time(int hour, int minute, int second)
    Parameters:hour(0-23),minute(0-59),second(0-59)
  • Time(long)–  Using a milliseconds time value it constructs a Time.
    public Time(long time)
    Parameters:time represented in milliseconds that from since January 1, 1970, 00:00:00 GMT

Program :Time(long)

import java.sql.Time;
public class SqlTimeExample{
public static void main(String[] args){
long current = System.currentTimeMillis();
Time time= new Time(current);
System.out.println("SqlTime: " + time);
}
}

Output:

SqlTime : 20:54:42

2. java.sql.Timemethods

  • setTime(long time):  In this method using a milliseconds time value seta Time object.
public void setTime(long time)

Parameters:  time 

Since January 1, 1970, 00:00:00 GMTrepresenteda timein milliseconds.

  • valueOf(String s):  Convert theJDBC time escape format into a Time value in this method.
public static Time valueOf(String s)

Parameters:  string s

 The timeis represented in the format “hh:mm:ss”.It returns the corresponding Time object.

  • toString(): this method formats the time in JDBC time escape format.
public String toString()

In this method, it has no parameters and it returns a String in hh:mm:ss format.

  • toInstant(): UnsupportedOperationException is thrown by this method and it is not used because no date component in SQL Time values.
public Instant toInstant()
  • toLocalTime(): In this method time object is converted to local time.
Public LocalTime toLocalTime()

In this method,thehour,minute, andsecond time valuesrepresented the same as in the Time object are represented.

Program: This program uses all the above-mentioned methods

import java.sql.*;
import java.time.LocalTime;
import java.time.Instant;
class SqlTimeExample2 {
public static void main(String args[]){
long milli = System.currentTimeMillis();
java.sql.Time time = new java.sql.Time(milli);
// display the time
System.out.println("old Time = " + time.toString());
// using setTime() method
long milli2 = 456732895489l;
time.setTime(milli2);
// using toString() method
System.out.println("New Time = " + time.toString());
// using valueOf() method
System.out.println("Value of 00:05:29 ="+ Time.valueOf("00:08:53"));
// using toLocalTime() method
System.out.println("localtime = " +time.toLocalTime());
// using toInstant() method
System.out.println("Instant= " +time.toInstant());
}
}

Output:

old Time = 23:08:08
New Time = 11:44:55
Value of 00:05:29 =00:08:53
localtime = 11:44:55
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.sql/java.sql.Time.toInstant(Time.java:281)
        at SqlTimeExample2.main(SqlTimeExample2.java:33)

Date and Time Format

The date and time functionality of java for displaying or utilizing we mostly use two classes they are:

  • DateFormat
  • SimpleDateFormat

java.text package these two classes are present.we use these two classes mostly in date and time formatting (converting date to string) and parsing (converting string to date).

The time is represented in different formats like AM/PM, 12 hrs,24 hrs, etc.

DateFormat:

The DateFormat is an abstract class used for formatting date/time subclasses. The time is represented as the time object and the date is represented as the date object as the millisecond since January 1,1970,00:00:00 GMT.

  • By default, many class methods are provided by the DateFormat for obtaining date/time formatter based on default or given locale and number of formatting styles.
  • SHORT, MEDIUM,LONG,and FULL are included in the formatting style.
  • For Format classit is the subclass. For formatting date, to date/time string we use the format(). This method is used for converting a given date/time into a particular format.
  • By using the method getTimeInstance() of DateFormat class we can create DateFormat object.
  • we need an instance of time for performing a time format, so for getting an instance of time we will be using the getTimeInstance() method.

Class hierarchy:

java.lang.Object

java.text.Format

java.text.DateFormat

Subclasses:   SimpleDateFormat

Program:

import java.text.DateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT);
System.out.println(dateFormat.format(new Date()));
dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println(dateFormat.format(new Date()));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
System.out.println(dateFormat.format(new Date()));
dateFormat = DateFormat.getTimeInstance(DateFormat.LONG);
System.out.println(dateFormat.format(new Date()));
dateFormat = DateFormat.getTimeInstance(DateFormat.FULL);
System.out.println(dateFormat.format(new Date()));
}
}

Output:

1:26:33 pm
1:26 pm
1:26:33 pm
1:26:33 pm IST
1:26:33 pm India Standard Time

SimpleDateFormat:

It is similar to the DateFormat. But in the SimpleDateFormat has locale support for formatting and parsing but in DateFormat there is no locale support. It is a concrete class anditextends DateFormat class.

SimpleDateFormatConstructors:

  • SimpleDateFormat(String pattern_args)
  • SimpleDateFormat(String pattern_args, Locale locale_args)
  • SimpleDateFormat(String pattern_args, DateFormatSymbolsformatSymbols)

Class hierarchy:

java.lang.Object

java.text.Format

java.text.DateFormat

java.text.SimpleDateFormat

  • We can create SimpleDateFormat by Using the SimpleDateFormat constructor, and it is  parametrized constructor and the parameter arestring pattern.
  • Date and time pattern strings are used to specify the Date and time formats. The pattern letters are‘A” to 'Z' and from 'a' to 'z' for representing the components of a date or time string.
  • To avoid interpretationusing single quotes (')Text can be quoted and all other characters are simply copied to the output string.
LetterTime ComponentExamples
aAm/pm markerPM
HAn hour in a day (0-23)0
kAn hour in a day (1-24)24
KAn hour in am/pm (0-11)0
hAn hour in am/pm (1-12)12
mMinute in hour30
sSecond in minute55
SMillisecond978
zTime zonePacific Standard Time; PST; GMT-08:00
ZTime zone-0800

Some Example programs for time format:

  • Using SimpleDateFormat format the time in AM-PM format:

Program:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Javatpoint{
public static void main(String[] args){
Date date = new Date();
String strDateFormat = "HH:mm:ss a";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println(sdf.format(date));
}
}

Output:

18:36:14 pm
  • Using SimpleDateFormat format the time in 24hrs format:

Program:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Javatpoint {
public static void main(String[] args) throws Exception {
Date d = new Date();
SimpleDateFormat simpDate;
simpDate = nargsimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(d));
}
}

Output:

19:39:24
  • Using SimpleDateFormat format the time in MMMM format:

Program:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Javatpoint{
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
System.out.println("Current Month in MMMM format: " + sdf.format(date));
}
}

Output:

Current Month in MMMM format: August
  • Using SimpleDateFormat format the time in 12hrs format:

Program:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Javatpoint {
public static void main(String[] args) throws Exception {
Date d = new Date();
SimpleDateFormat simpDate;
simpDate = nargsimpleDateFormat("KK:mm:ss");
System.out.println(simpDate.format(d));
}
}

Output:

07:43:11

Related Topics

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.