Saturday, 10 September 2022

Convert java.sql.Date to java.util.Date in Java

java.util.Date

‘java.util.Date’ class is used to represent a specific instant in time, with millisecond precision since the 1st of January 1970 00:00:00 GMT (the epoch time).

 

How to get an instance of Date class?

Following constructors are used to get an instance of java.util.Date class.

 

public Date()

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

 

public Date(long date)

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

 

java.util.Date object is not immutable

Date object is mutable, you can change the date using setTime method.

date1.setTime(0);	// Thu Jan 01 05:30:00 IST 1970
date2.setTime(1111111111111l);	// Fri Mar 18 07:28:31 IST 2005

 

Find the below working application.

 

JavaUtilDateDemo.java
package com.sample.app.time;

import java.util.Date;

public class JavaUtilDateDemo {

	public static void main(String[] args) {
		Date date1 = new Date();
		Date date2 = new Date(1642516388900l);

		System.out.println("date1 : " + date1);
		System.out.println("date2 : " + date2);

		// Update date1 and date2 objects.
		date1.setTime(0);	// Thu Jan 01 05:30:00 IST 1970
		date2.setTime(1111111111111l);	// Fri Mar 18 07:28:31 IST 2005

		System.out.println("\n\ndate1 : " + date1);
		System.out.println("date2 : " + date2);

	}

}

Output

date1 : Sat Sep 10 12:20:12 IST 2022
date2 : Tue Jan 18 20:03:08 IST 2022


date1 : Thu Jan 01 05:30:00 IST 1970
date2 : Fri Mar 18 07:28:31 IST 2005

java.sql.Date

java.sql.Date class extends java.util.Date class.

 

public class Date extends java.util.Date {
	...........
	...........
}

java.sql.Date class is used to model a Date object whenever we want to work with DATE type in SQL. To conform with the definition of SQL DATE type, the millisecond values wrapped by a java.sql.Date instance are normalized by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

java.sql.Date sqlDate = new java.sql.Date(1642516388900l);	// 2022-01-18
java.util.Date utilDate = new java.util.Date(1642516388900l);	// Tue Jan 18 20:03:08 IST 2022

Find the below working application.

 

JavaSqlDateDemo.java

package com.sample.app.time;

public class JavaSqlDateDemo {

	public static void main(String[] args) {
		java.sql.Date sqlDate = new java.sql.Date(1642516388900l);	// 2022-01-18
		java.util.Date utilDate = new java.util.Date(1642516388900l);	// Tue Jan 18 20:03:08 IST 2022

		System.out.println("sqlDate : " + sqlDate);
		System.out.println("utilDate : " + utilDate);
	}

}

Output

sqlDate : 2022-01-18
utilDate : Tue Jan 18 20:03:08 IST 2022

Just like java.util.Date class, java.sql.Date class is also mutable.

 

In summary, java.util.Date object stores a date plus time information (Tue Jan 18 20:03:08 IST 2022) as milliseconds since the epoch, whereas java.sql.Date stores date only (2022-01-18).

 

How to convert java.sql.Date to java.util.Date?

Get java.sql.Date object time in milliseconds.


java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
long timeInMillis = sqlDate.getTime();

Get the java.util.Date object using timeInMillis.

java.util.Date utilDate = new java.util.Date(timeInMillis);

DateConverter.java

package com.sample.app.time;

public class DateConverter {

	public static void main(String[] args) {
		java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
		long timeInMillis = sqlDate.getTime();
		
		java.util.Date utilDate = new java.util.Date(timeInMillis);

		System.out.println("sqlDate : " + sqlDate);
		System.out.println("utilDate : " + utilDate);
	}

}

Output

utilDate : Sun Sep 11 02:37:16 IST 2022
sqlDate : 2022-09-11



Previous                                                 Next                                                 Home



You may like

Date and time programs

Convert java.util.Date to calendar

Get current date and time using LocalDate, LocalTime, LocalDateTime

Convert time from 12 hour format to 24 hour format

Convert time from 24 hour format to 12 hour format

Convert java.util.Date to java.sql.Date in Java

How to break out of nested loops in Java?

In this post, I am going to explain how to break the outer loop in Java.

 

Approach 1: Using labelled break statement.

 

labelled break

label is a group of statements, identified by using labelname.

 

Syntax

labelName: {
      statement 1
      statement 2
      …....
      statement N
    }

 

Syntax to break the label

break labelName;

 

BreakOuterLoopDemo1.java

package com.sample.app.loops;

public class BreakOuterLoopDemo1 {

	public static void main(String[] args) {
		outerLoop: 
			for (int i = 1; i < 10; i++) {
				for (int j = 1; j < 10; j++) {
					if (i * j > 5) {
						System.out.println("Breaking outer loop");
						break outerLoop;
					} else {
						System.out.println("(" + i + "," + j + ")");
					}
				}
				System.out.println("Inner loop executed....");
			}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 2: Keep the looping logic in a different method, and return from the method, when you meet the criteria.

 

BreakOuterLoopDemo2.java

package com.sample.app.loops;

public class BreakOuterLoopDemo2 {

	public static void doSomeLogic() {
		for (int i = 1; i < 10; i++) {
			for (int j = 1; j < 10; j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					return;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

	public static void main(String[] args) {
		doSomeLogic();
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 3: With the help of a Boolean flag.

 

BreakOuterLoopDemo3.java

package com.sample.app.loops;

public class BreakOuterLoopDemo3 {

	public static void main(String[] args) {
		boolean flag = true;

		for (int i = 1; (i < 10 && flag); i++) {
			for (int j = 1; (j < 10 && flag); j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					flag = false;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop
Inner loop executed....

 


 
 

You may like

Interview Questions

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

Convert string to InputStream in Java

InputStream is an abstract superclass of all classes representing an input stream of bytes.

 

By initializing the ByteArrayInputStream using string byte array, we can get a InputStream object with string content.

String str = "line 1\nline 2\nline 3";
InputStream inputStream = new ByteArrayInputStream(str.getBytes()

Find the below working application.

 

StringToInputStreamDemo1.java

package com.sample.app.streams;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamDemo1 {

	public static void main(String[] args) {
		String str = "line 1\nline 2\nline 3";

		try (InputStream inputStream = new ByteArrayInputStream(str.getBytes());
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {

			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println(info);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Output

line 1
line 2
line 3

Get the InputStream from substring of string

Using the following constrcutor, we can get the InputStream from the string substring.

 

public ByteArrayInputStream(byte buf[], int offset, int length) 

'offset' specifies the offset in the buffer of the first byte to read and 'length' specifies the maximum number of bytes to read from the buffer.

 

Example

String str = "line 1\nline 2\nline 3";
InputStream inputStream = new ByteArrayInputStream(str.getBytes(), 7, 7);

Find the below working application.


 

StringToInputStreamDemo2.java

package com.sample.app.streams;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamDemo2 {

	public static void main(String[] args) {
		String str = "line 1\nline 2\nline 3";

		try (InputStream inputStream = new ByteArrayInputStream(str.getBytes(), 7, 7);
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {

			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println(info);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

Output

line 2



You may like

file and stream programs in Java

Convert OutputStream to String in Java

Write byte array to a file

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to get the directory size in Java?

Convert OutputStream to String in Java

‘java.io.OutputStream’  is the abstract superclass of all the classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink/destination.

 

Following examples explain how to convert different a ByteArrayOutputStream object to string in Java.

 

Example 1: Convert ByteArrayOutputStream to string.

 

Get the byte array from ByteArrayOutputStream object.

byte[] byteArr = byteArrayOutputStream.toByteArray();

Initialize the string using byte array.

String str2 = new String(byteArr);

Find the below working application.

 

OutputStreamToStringDemo1.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OutputStreamToStringDemo1 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			byte[] byteArr = byteArrayOutputStream.toByteArray();
			String str2 = new String(byteArr);

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!

Example 2: Using toString method of ByteArrayOutputStream.

ByteArrayOutputString#toString method converts the buffer's contents into a string decoding bytes using the platform's default character set.

String str2 = byteArrayOutputStream.toString();

OutputStreamToStringDemo2.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OutputStreamToStringDemo2 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			String str2 = byteArrayOutputStream.toString();

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!

You can even set the character set to decode the byte array to string using following toString methods.

public synchronized String toString(Charset charset)

public synchronized String toString(String charsetName)

Converts the buffer's contents into a string by decoding the bytes using the specified charset.

 

An invocation of this method of the form

String str = byteArrayOutputStream.toString("UTF-8");

 

behaves in exactly the same way as the below expression.

String str = byteArrayOutputStream.toString(StandardCharsets.UTF_8);

 


OutputStreamToStringDemo3.java

package com.sample.app.streams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class OutputStreamToStringDemo3 {

	public static void main(String[] args) throws IOException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String str1 = "Hello World!!!!";
			byteArrayOutputStream.write(str1.getBytes());

			String str2 = byteArrayOutputStream.toString("UTF-8");
			String str3 = byteArrayOutputStream.toString(StandardCharsets.UTF_8);

			System.out.println("str1 : " + str1);
			System.out.println("str2 : " + str2);
			System.out.println("str3 : " + str3);
		}

	}

}

Output

str1 : Hello World!!!!
str2 : Hello World!!!!
str3 : Hello World!!!!



You may like

Copy the content of file to other location

Write byte array to a file

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to get the directory size in Java?