Java Date Conversion Examples

Java Date Conversion Examples

In this tutorial, I am attaching some programs about, Java Date Conversion Examples. such as Converting java.util.Date to java.sql.Date and Converting java.sql.Date to java.util.Date. same Java Date Conversion Examples has been shared in the post.

Converting java.util.Date to java.sql.Date

// Converting java.util.Date to java.sql.Date
	public static java.sql.Date convertUtilDateToSQLDate(java.util.Date utilDate) {

		java.sql.Date sqlDate = null;
		
		if(utilDate != null) {
		
			try {
				
				// Conversion
				sqlDate = new java.sql.Date(utilDate.getTime());
				
			} catch(Exception ex) {
				
				System.out.println(ex.getMessage());
				ex.printStackTrace();
			}
		}
		
		return sqlDate;
	}

Converting java.sql.Date to java.util.Date

// Converting java.sql.Date to java.util.Date
	public static java.util.Date convertSQLDateToUtilDate(java.sql.Date sqlDate) {

		java.util.Date utilDate = null;
		
		if(sqlDate != null) {
		
			try {
				
				// Conversion
				utilDate = new java.util.Date(sqlDate.getTime());
				
			} catch(Exception ex) {
				
				System.out.println(ex.getMessage());
				ex.printStackTrace();
			}
		}
		
		return utilDate;
	}

Final Example

DateConversion.java

package com.dineshkrish.date;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class DateConversion {

	// Converting java.util.Date to java.sql.Date
	public static java.sql.Date convertUtilDateToSQLDate(java.util.Date utilDate) {

		java.sql.Date sqlDate = null;
		
		if(utilDate != null) {
		
			try {
				
				// Conversion
				sqlDate = new java.sql.Date(utilDate.getTime());
				
			} catch(Exception ex) {
				
				System.out.println(ex.getMessage());
				ex.printStackTrace();
			}
		}
		
		return sqlDate;
	}

	// Converting java.sql.Date to java.util.Date
	public static java.util.Date convertSQLDateToUtilDate(java.sql.Date sqlDate) {

		java.util.Date utilDate = null;
		
		if(sqlDate != null) {
		
			try {
				
				// Conversion
				utilDate = new java.util.Date(sqlDate.getTime());
				
			} catch(Exception ex) {
				
				System.out.println(ex.getMessage());
				ex.printStackTrace();
			}
		}
		
		return utilDate;
	}

	public static void main(String[] args) {
		
	
		// Defining Date Object
		java.util.Date date = new java.util.Date();
		
		// Converting java.util.Date to java.sql.Date
		java.sql.Date sqlDate = convertUtilDateToSQLDate(date);
		
		System.out.println(sqlDate+" ("+sqlDate.getClass()+")");

		// Converting java.sql.Date to java.util.Date
		java.util.Date utilDate = convertSQLDateToUtilDate(sqlDate);
		
		System.out.println(utilDate+" ("+utilDate.getClass()+")");
		
	}
	
}

Output

2016-11-28 (class java.sql.Date)
Mon Nov 28 14:55:51 IST 2016 (class java.util.Date)

References

1. java.util.Date API
2. java.sql.Date API