×

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 Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.