Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

Monday, 15 April 2024

Utility class to convert the time in double to different time formats like days, hours, minutes, seconds etc.,

Time is a fundamental aspect of programming, and in Java, it's essential to understand the different units of time and how they relate to each other. Whether you're working with nanoseconds, milliseconds, seconds, or days, being able to convert between these units is crucial for various applications. In this blog post, we'll delve into the intricacies of time dimensions and provide utility classes to convert between them seamlessly.

 

The Basics: Time Units

Before we dive into conversions, let's establish the basic units of time we'll be working with:

 

1.   Nanoseconds (ns): The smallest unit of time commonly used in programming. It represents one billionth of a second.

2.   Microseconds (μs): One thousand nanoseconds make up a microsecond.

3.   Milliseconds (ms): A millisecond is equal to one thousand microseconds or one million nanoseconds.

4.   Seconds (s): A standard unit of time, where one second equals one thousand milliseconds.

5.   Minutes (min): Sixty seconds make up a minute.

6.   Hours (hr): An hour consists of sixty minutes.

7.   Days (d): A day comprises twenty-four hours.

 

Now that we have a grasp of these time dimensions, let's explore how we can convert between them efficiently.

 

Example: Calculate number of seconds per day.

To calculate the number of seconds in one day, you need to consider that there are 24 hours in a day, 60 minutes in an hour, and 60 seconds in a minute. So, you can use the following formula:

 

seconds = days × 24 × 60 × 60

seconds=days×24×60×60

 

Let's compute it for one day

 

seconds = 1 × 24 × 60 × 60 = 86,400

 

So, there are 86,400 seconds in one day.

 

 

Utility Class for Time Conversion

To facilitate time conversions in Java, we can create a utility class that encapsulates the conversion logic. Below is a Java class TimeConverter that provides static methods for converting between different time units.

 

TimeConverter.java

package com.sample.app.util;

import java.util.concurrent.TimeUnit;

public final class TimeConverter {

	private static final long ONE_NANO_SECOND = 1L;

	private static final long ONE_MICRO_SECOND_TO_NANO = ONE_NANO_SECOND * 1000L;

	private static final long ONE_MILLI_SECOND_TO_NANO = ONE_MICRO_SECOND_TO_NANO * 1000L;

	private static final long ONE_SECOND_TO_NANO = ONE_MILLI_SECOND_TO_NANO * 1000L;

	private static final long ONE_MINUTE_TO_NANO = ONE_SECOND_TO_NANO * 60L;

	private static final long ONE_HOUR_TO_NANO = ONE_MINUTE_TO_NANO * 60L;

	private static final long ONE_DAY_TO_NANO = ONE_HOUR_TO_NANO * 24L;

	private TimeConverter() {
	}

	public static double convert(double t, TimeUnit sourceUnit, TimeUnit destinationUnit) {
		switch (sourceUnit) {
		case NANOSECONDS:
			return nanosToUnit(t, destinationUnit);
		case MICROSECONDS:
			return microsToUnit(t, destinationUnit);
		case MILLISECONDS:
			return millisToUnit(t, destinationUnit);
		case SECONDS:
			return secondsToUnit(t, destinationUnit);
		case MINUTES:
			return minutesToUnit(t, destinationUnit);
		case HOURS:
			return hoursToUnit(t, destinationUnit);
		case DAYS:
		default:
			return daysToUnit(t, destinationUnit);
		}
	}

	public static double nanosToUnit(double nanos, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
		default:
			return nanos;
		case MICROSECONDS:
			return nanos / (ONE_MICRO_SECOND_TO_NANO / ONE_NANO_SECOND);
		case MILLISECONDS:
			return nanos / (ONE_MILLI_SECOND_TO_NANO / ONE_NANO_SECOND);
		case SECONDS:
			return nanos / (ONE_SECOND_TO_NANO / ONE_NANO_SECOND);
		case MINUTES:
			return nanos / (ONE_MINUTE_TO_NANO / ONE_NANO_SECOND);
		case HOURS:
			return nanos / (ONE_HOUR_TO_NANO / ONE_NANO_SECOND);
		case DAYS:
			return nanos / (ONE_DAY_TO_NANO / ONE_NANO_SECOND);
		}
	}

	public static double microsToUnit(double micros, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return micros * (ONE_MICRO_SECOND_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
		default:
			return micros;
		case MILLISECONDS:
			return micros / (ONE_MILLI_SECOND_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case SECONDS:
			return micros / (ONE_SECOND_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MINUTES:
			return micros / (ONE_MINUTE_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case HOURS:
			return micros / (ONE_HOUR_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case DAYS:
			return micros / (ONE_DAY_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		}
	}

	public static double millisToUnit(double millis, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return millis * (ONE_MILLI_SECOND_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
			return millis * (ONE_MILLI_SECOND_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MILLISECONDS:
		default:
			return millis;
		case SECONDS:
			return millis / (ONE_SECOND_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case MINUTES:
			return millis / (ONE_MINUTE_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case HOURS:
			return millis / (ONE_HOUR_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case DAYS:
			return millis / (ONE_DAY_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		}
	}

	public static double secondsToUnit(double seconds, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return seconds * (ONE_SECOND_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
			return seconds * (ONE_SECOND_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MILLISECONDS:
			return seconds * (ONE_SECOND_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case SECONDS:
		default:
			return seconds;
		case MINUTES:
			return seconds / (ONE_MINUTE_TO_NANO / ONE_SECOND_TO_NANO);
		case HOURS:
			return seconds / (ONE_HOUR_TO_NANO / ONE_SECOND_TO_NANO);
		case DAYS:
			return seconds / (ONE_DAY_TO_NANO / ONE_SECOND_TO_NANO);
		}
	}

	public static double minutesToUnit(double minutes, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return minutes * (ONE_MINUTE_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
			return minutes * (ONE_MINUTE_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MILLISECONDS:
			return minutes * (ONE_MINUTE_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case SECONDS:
			return minutes * (ONE_MINUTE_TO_NANO / ONE_SECOND_TO_NANO);
		case MINUTES:
		default:
			return minutes;
		case HOURS:
			return minutes / (ONE_HOUR_TO_NANO / ONE_MINUTE_TO_NANO);
		case DAYS:
			return minutes / (ONE_DAY_TO_NANO / ONE_MINUTE_TO_NANO);
		}
	}

	public static double hoursToUnit(double hours, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return hours * (ONE_HOUR_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
			return hours * (ONE_HOUR_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MILLISECONDS:
			return hours * (ONE_HOUR_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case SECONDS:
			return hours * (ONE_HOUR_TO_NANO / ONE_SECOND_TO_NANO);
		case MINUTES:
			return hours * (ONE_HOUR_TO_NANO / ONE_MINUTE_TO_NANO);
		case HOURS:
		default:
			return hours;
		case DAYS:
			return hours / (ONE_DAY_TO_NANO / ONE_HOUR_TO_NANO);
		}
	}

	public static double daysToUnit(double days, TimeUnit destinationUnit) {
		switch (destinationUnit) {
		case NANOSECONDS:
			return days * (ONE_DAY_TO_NANO / ONE_NANO_SECOND);
		case MICROSECONDS:
			return days * (ONE_DAY_TO_NANO / ONE_MICRO_SECOND_TO_NANO);
		case MILLISECONDS:
			return days * (ONE_DAY_TO_NANO / ONE_MILLI_SECOND_TO_NANO);
		case SECONDS:
			return days * (ONE_DAY_TO_NANO / ONE_SECOND_TO_NANO);
		case MINUTES:
			return days * (ONE_DAY_TO_NANO / ONE_MINUTE_TO_NANO);
		case HOURS:
			return days * (ONE_DAY_TO_NANO / ONE_HOUR_TO_NANO);
		case DAYS:
		default:
			return days;
		}
	}

	public static void main(String args[]) {
		double oneDayToNano = daysToUnit(1, TimeUnit.NANOSECONDS);
		double oneHourToNano = hoursToUnit(1, TimeUnit.NANOSECONDS);
		double oneMinuteToNano = minutesToUnit(1, TimeUnit.NANOSECONDS);
		double oneSecondToNano = secondsToUnit(1, TimeUnit.NANOSECONDS);
		double oneMilliToNano = millisToUnit(1, TimeUnit.NANOSECONDS);
		double oneMicroToNano = microsToUnit(1, TimeUnit.NANOSECONDS);
		double oneNanoToNano = nanosToUnit(1, TimeUnit.NANOSECONDS);

		System.out.println("oneDayToNano : " + oneDayToNano);
		System.out.println("oneHourToNano : " + oneHourToNano);
		System.out.println("oneMinuteToNano : " + oneMinuteToNano);
		System.out.println("oneSecondToNano : " + oneSecondToNano);
		System.out.println("oneMilliToNano : " + oneMilliToNano);
		System.out.println("oneMicroToNano : " + oneMicroToNano);
		System.out.println("oneNanoToNano : " + oneNanoToNano);

		double oneDayToSeconds = daysToUnit(1, TimeUnit.SECONDS);
		double oneHourToSeconds = hoursToUnit(1, TimeUnit.SECONDS);
		double oneMinuteToSeconds = minutesToUnit(1, TimeUnit.SECONDS);
		double oneSecondToSeconds = secondsToUnit(1, TimeUnit.SECONDS);
		double oneMilliToSeconds = millisToUnit(1, TimeUnit.SECONDS);
		double oneMicroToSeconds = microsToUnit(1, TimeUnit.SECONDS);
		double oneNanoToSeconds = nanosToUnit(1, TimeUnit.SECONDS);

		System.out.println("\noneDayToSeconds : " + oneDayToSeconds);
		System.out.println("oneHourToSeconds : " + oneHourToSeconds);
		System.out.println("oneMinuteToSeconds : " + oneMinuteToSeconds);
		System.out.println("oneSecondToSeconds : " + oneSecondToSeconds);
		System.out.println("oneMilliToSeconds : " + oneMilliToSeconds);
		System.out.println("oneMicroToSeconds : " + oneMicroToSeconds);
		System.out.println("oneNanoToSeconds : " + oneNanoToSeconds);
	}

}

 

Output

oneDayToNano : 8.64E13
oneHourToNano : 3.6E12
oneMinuteToNano : 6.0E10
oneSecondToNano : 1.0E9
oneMilliToNano : 1000000.0
oneMicroToNano : 1000.0
oneNanoToNano : 1.0

oneDayToSeconds : 86400.0
oneHourToSeconds : 3600.0
oneMinuteToSeconds : 60.0
oneSecondToSeconds : 1.0
oneMilliToSeconds : 0.001
oneMicroToSeconds : 1.0E-6
oneNanoToSeconds : 1.0E-9

In summary, time dimensions and being able to convert between them is essential for various Java applications. With the utility class provided, you can seamlessly convert time units with ease. Feel free to extend the TimeConverter class to include additional conversions or refine the existing ones to suit your specific needs.

 

Time is indeed of the essence in programming, and mastering its dimensions empowers you to build robust and efficient solutions.



Previous                                                    Next                                                    Home

Friday, 5 April 2024

Mastering Date-Time Formatting in Java with DateTimeFormatterBuilder

In Java programming, handling date and time values is a fundamental aspect of many applications. Whether it's displaying dates in a specific format, parsing user input, or manipulating temporal data, having a reliable toolset is crucial. This is where Java's DateTimeFormatter and DateTimeFormatterBuilder classes come into play. These classes provide powerful capabilities for formatting and parsing date-time values according to various patterns and requirements.

 

Understanding DateTimeFormatter

The DateTimeFormatter class is a cornerstone of Java's date and time API (introduced in Java 8 as part of the java.time package). It offers a robust framework for formatting and parsing date-time objects. With DateTimeFormatter, developers can easily convert date-time values to and from strings, adhering to specific patterns and conventions.

 

The Role of DateTimeFormatterBuilder

While DateTimeFormatter serves as the primary tool for formatting and parsing date-time values, DateTimeFormatterBuilder enhances its functionality by allowing developers to construct custom formatter instances programmatically. Think of it as a specialized builder class dedicated to crafting precise DateTimeFormatter objects tailored to specific requirements.

 

CustomDateTimeFormatterExample.java

package com.sample.app;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

public class CustomDateTimeFormatterExample {
	public static void main(String[] args) {
		DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4) // Year
				.appendLiteral("-").appendValue(ChronoField.MONTH_OF_YEAR, 2) // Month
				.appendLiteral("-").appendValue(ChronoField.DAY_OF_MONTH, 2) // Day
				.appendLiteral(" ").appendValue(ChronoField.HOUR_OF_DAY, 2) // Hour
				.appendLiteral(":").appendValue(ChronoField.MINUTE_OF_HOUR, 2) // Minute
				.appendLiteral(":").appendValue(ChronoField.SECOND_OF_MINUTE, 2) // Second
				.toFormatter();

		String formattedDateTime = formatter.format(LocalDateTime.now());
		System.out.println("Formatted Date-Time: " + formattedDateTime);
	}
}

 

Output

Formatted Date-Time: 2024-04-05 14:23:32

Following utility class gets the LocalDateTime object from the data time string.

 

DateUtil.java

package com.sample.app.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DateUtil {

	enum DateTimePattern {
		PATTERN_RFC1123("EEE, dd MMM yyyy HH:mm:ss zzz"), PATTERN_ISO_OFFSET_DATE_TIME("yyyy-MM-dd'T'HH:mm:ssXXX"),
		PATTERN_ISO_INSTANT("yyyy-MM-dd'T'HH:mm:ss'Z'"), PATTERN_RFC_3339("yyyy-MM-dd'T'HH:mm:ssXXX"),
		PATTERN_HTTP_DATE("EEE, dd MMM yyyy HH:mm:ss zzz"), PATTERN_ATOM("yyyy-MM-dd'T'HH:mm:ssXXX"),
		PATTERN_RFC_1123_DATE_TIME("EEE, dd MMM yyyy HH:mm:ss zzz");

		private final String pattern;

		DateTimePattern(String pattern) {
			this.pattern = pattern;
		}

		public String getPattern() {
			return pattern;
		}
	}

	public static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = new ArrayList<>();

	static {

		DateTimePattern[] patterns = DateTimePattern.values();

		for (DateTimePattern pattern : patterns) {
			try {
				DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseLenient().parseCaseInsensitive()
						.appendPattern(pattern.getPattern()).toFormatter(Locale.ENGLISH);
				DATE_TIME_FORMATTERS.add(formatter);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private static LocalDateTime parseDate(final String dateValue, final List<DateTimeFormatter> dateFormatters) {

		for (final DateTimeFormatter dateFormatter : dateFormatters) {
			try {

				return LocalDateTime.from(dateFormatter.parse(dateValue));
				// return Instant.from(dateFormatter.parse(dateValue));
			} catch (final DateTimeParseException ignore) {
			}
		}
		return null;
	}

	public static LocalDateTime parseStandardDate(final String dateValue) {
		return parseDate(dateValue, DATE_TIME_FORMATTERS);
	}

}

DateUtilDemo.java

package com.sample.app;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.sample.app.util.DateUtil;

public class DateUtilDemo {

	public static void main(String[] args) {
		List<String> exampleValues = new ArrayList<>(Arrays.asList("Sun, 06 Nov 1994 08:49:37 GMT", // PATTERN_RFC1123
				"2024-04-05T13:45:30+03:00", // PATTERN_ISO_OFFSET_DATE_TIME
				"2024-04-05T13:45:30Z", // PATTERN_ISO_INSTANT
				"Sun, 06 Nov 1994 08:49:37 GMT", // PATTERN_RFC_3339
				"2024-04-05T13:45:30+03:00", // PATTERN_HTTP_DATE
				"2024-04-05T13:45:30+03:00", // PATTERN_ATOM
				"Sun, 06 Nov 1994 08:49:37 GMT" // PATTERN_RFC_1123_DATE_TIME
		));

		for (String sampleDate : exampleValues) {
			try {
				LocalDateTime instant = DateUtil.parseStandardDate(sampleDate);
				System.out.println("For the pattern " + sampleDate + " instant : " + instant);
			} catch (Exception e) {
				System.err.println("Error for pattern " + sampleDate + " error :");
				e.printStackTrace();
			}

		}

	}

}

Output

For the pattern Sun, 06 Nov 1994 08:49:37 GMT instant : 1994-11-06T08:49:37
For the pattern 2024-04-05T13:45:30+03:00 instant : 2024-04-05T13:45:30
For the pattern 2024-04-05T13:45:30Z instant : 2024-04-05T13:45:30
For the pattern Sun, 06 Nov 1994 08:49:37 GMT instant : 1994-11-06T08:49:37
For the pattern 2024-04-05T13:45:30+03:00 instant : 2024-04-05T13:45:30
For the pattern 2024-04-05T13:45:30+03:00 instant : 2024-04-05T13:45:30
For the pattern Sun, 06 Nov 1994 08:49:37 GMT instant : 1994-11-06T08:49:37

 

Previous                                                 Next                                                 Home

Monday, 27 November 2023

Get the current date, with the milliseconds removed

Following snippet return a new Date object by removing the milliseconds.

public static Date removeMilliSeconds(Date date) {
	// Get the number of milliseconds since January 1, 1970, 00:00:00 GMT
	// represented by this Date object.
	long timeInMilliSeconds = date.getTime();
	long timeInSeconds = timeInMilliSeconds / 1000;

	return new Date(timeInSeconds * 1000L);
}

Explanation:

a.   The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT (the epoch).

b.   The variable timeInMilliSeconds stores the time represented by the input Date object in milliseconds.

c.    The code then converts this time from milliseconds to seconds by dividing timeInMilliSeconds by 1000, resulting in timeInSeconds.

d.   Finally, a new Date object is created using the time in seconds. The multiplication by 1000L is done to convert the time back to milliseconds, and this effectively sets the milliseconds part to zero, as it is now a multiple of 1000.

 

In summary, the purpose of this method is to remove the milliseconds from a given Date object by creating a new Date object with the same date and time but with the milliseconds set to zero.

 

Find the below working application.

 

RemoveMilliSecondsFromDate.java

package com.sample.app;

import java.text.SimpleDateFormat;
import java.util.Date;

public class RemoveMilliSecondsFromDate {

	public static Date removeMilliSeconds(Date date) {

		// Get the number of milliseconds since January 1, 1970, 00:00:00 GMT
		// represented by this Date object.
		long timeInMilliSeconds = date.getTime();
		long timeInSeconds = timeInMilliSeconds / 1000;

		return new Date(timeInSeconds * 1000L);
	}

	public static String formattedDateStr(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		return sdf.format(date);
	}

	public static void main(String[] args) {
		Date date = new Date();

		System.out.println("date : " + formattedDateStr(date));
		System.out.println("date after removing milliseconds: " + formattedDateStr(removeMilliSeconds(date)));
	}

}

Output

date : 2023-11-28 10:28:08.233
date after removing milliseconds: 2023-11-28 10:28:08.000

 

Previous                                                 Next                                                 Home

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