Java Date utilities Functions

Connect with

Java Date formatThis article of Java Date format examples explain about different examples of string to date java and Java date to string format.

1. Overview of Java Date Format examples

In this article, on Java date format examples, you will learn from Java date to string and string to date Java. In any project of java, you must encounter the conversion between the Java date to string and string to date in java, so I thought to write an article for you to ease out this Java Date utilities functions.

When you work in any application on a day-to-day basis you have to convert from string date to java Date and java date to string date. And converting is a little bit tricky, and Java Date util function should be separate out in one class so that you can re-use those methods in different places and different layers of the application.

2. Why conversion required?

There are so many reasons to convert from one format to another format of Date in Java.

  • when you pull from DB you return one format and showcase your presentation layer in another format.
  • when you push to date in DB, get one type of format and convert into another format to push
  • you usually showcase on UI in a Local specific format of a date.
  • from UI to DB you have to convert from one format to another and vice-versa
  • showcase of the date on UI depends on business user demands, so you have to convert from one to another format.

3. Different format of Dates

A few of the Java date format examples mentioned here but not limited to, you can use more than this format as per your project or module need.

package com.mysoftkey.springrest.service;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

/**
 * This utility class is used to manipulation for Date stuff in java.
 * 
 * @author ranjeet jha
 *
 */
public class DateUtil  {

 private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);
 // format of date used in this project.
 public static final String DATE_FORMAT_DD_MMM_YY_DEFAULT = "dd-MMM-yy";
  public static final String DATE_FORMAT_DD_MMM_YY_HH_MM_SS = "dd-MMM-yy hh.mm.ss";
  public static final String DATE_FORMAT_DD_MMM_YY_HH_MM_SS_ = "dd-MMM-yy HH:mm:ss";
  public static final String DATE_FORMAT_DD_MM_YYYY_HH_MM_SS = "dd-MM-yyyy hh:mm:ss";
  public static final String DATE_FORMAT_DD_MMMM_YYYY = "dd MMM yyy";
  public static final String DATE_FORMAT_DD_MM_YYYY = "dd-MM-yyyy";
  public static final String DATE_FORMAT_MM_DD_YYYY_FOR_SQL = "MM-dd-yyyy";
  public static final String DATE_FORMAT_MM_DD_YYYY = "MM/dd/yyyy";
  public static final String DATE_FORMAT_DD_MM_YYYY_SLASH = "dd/MM/yyyy";
  public static final String DATE_FORMAT_DD_MM_YY_SLASH = "dd/MM/yy";
  public static final String DATE_FORMAT_EE_MMM_dd_hh_mm_ss_z_yyyy = "EEE MMM dd hh:mm:ss z yyyy";
  public static final String DATE_FORMAT_yyyy_MM_dd_T_HH_mm_ss_Z = "yyyy-MM-dd'T'HH:mm:ss'Z'";
  public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
  public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
  public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";
  public static final String DATE_FORMAT_YYYY_MM_DD_hh_MM_SS_MILLI = "yyyy-MM-dd HH:mm:ss.S"; 
  public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS_MILLI = "yyyy-MM-dd HH:mm:ss.sss";
  public static final String DATE_FORMAT_DD_MMM_YYYY_HH_MM_SS = "dd MMM yyyy HH:mm:ss";
  public static final String DATE_FORMAT_YYYYMMDD_HHMMSS = "yyyyMMdd_hhmmss";
  public static final String DATE_FORMAT_DDMMYYYY_HHMMSS = "dd/MM/yyyy HH:mm:ss";
  public static final String DATE_FORMAT_MMDDYYYY_HHMMSS_AMPM = "MM/dd/yyyy hh:mm:ss a";

 // all the methods below place here.
---
}

4. Java.util.Date to String formated date

In this section, you learn about how to convert Java Date to string formated Date.

 /**
  * This method is used to get formatted string date from Java Date.
  * 
  * @param date
  * @param format
  * @return
  */
 public static String parseDate(Date date, String format) {
  SimpleDateFormat dateFormat = null;
  String sDate = null;
  try {
   if (format != null) {
    dateFormat = new SimpleDateFormat(format);
   } else {
    dateFormat = new SimpleDateFormat(DATE_FORMAT_DD_MMM_YY_DEFAULT);
   }
   sDate = dateFormat.format(date);
  } catch (Exception e) {
   logger.warn(e.getMessage());
  }
  return sDate;
 }

5. String Date to Java Date Format

In this section you learn about how to convert Java Date of string to Java date.

/**
  * This method is used to parse string date to {@link Date}.
  * 
  * @param dateStr
  *         e.g. "Tue Jan 01 05:30:00 IST 1985";
  * @param format
  *         e.g. "EEE MMM dd hh:mm:ss z yyyy";
  * @return
  */
 public static Date getStringToDate(String dateStr, String format) {
  Date d = null;
  SimpleDateFormat dateFormat = null;
  try {
   if (dateStr != null && format != null) {
    // String format = "EEE MMM dd hh:mm:ss z yyyy"; // value e.g.
    // "Tue Jan 01 05:30:00 IST 1985";
    dateFormat = new SimpleDateFormat(format);
    d = dateFormat.parse(dateStr);
   }

  } catch (Exception e) {
   logger.info("error in parsing dateStr [" + dateStr + "] , format [ " + format + " ] , msg: " + e.getMessage());
  } finally {
   dateFormat = null;
  }
  return d;
 }

6. Java Date to string date format

 public static String getFormatedDate(SimpleDateFormat sdf, Date d) {
  try {
   return sdf.format(d);
  } catch (Exception e) {
   logger.error("exception occured while formating date, msg : " + e.getMessage());
  }
  return null;
 }

7. Add Days in java.util.Date

public static Date addDays(Date date, int daysToAdd) {
  Date newDate = null;
  if (date != null) {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.add(Calendar.DATE, daysToAdd);
   newDate = cal.getTime();
  }
  return newDate;
 }

8. Add days in current Date

public static Date addDaysInCurrentDate(int daysToAdd) {
  Calendar cal = Calendar.getInstance();
  cal.add(Calendar.DATE, daysToAdd);
  return cal.getTime();
 }

9. Add minutes to java.util.Date

 public static Date addMinute(Date date, int min) {
  Date newDate = null;
  if (date != null) {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.add(Calendar.MINUTE, min);
   newDate = cal.getTime();
  }
  return newDate;
 }

10. Date validate function

public static boolean isThisDateValid(String dateToValidate, String dateFromat) {

  if (dateToValidate == null) {
   return false;
  }

  SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
  sdf.setLenient(false);

  try {

   // if not valid, it will throw ParseException
   Date date = sdf.parse(dateToValidate);

  } catch (ParseException e) {
   return false;
  }

  return true;
 }

11. Get Current year

 public static int getCurrentYear() {

  int year = Calendar.getInstance().get(Calendar.YEAR);
  return year;
 }

12. Get Current month

 public static int getCurrentMonth() {
  // month start from 0 so adding 1 into it
  int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
  return month;
 }

13. Get days difference between two Dates

In this section you learn about how to get difference between tow Java Date.

public static int getDifferenceDate(Date d2, Date d1) {
  int day = 0;
  if (null != d2 && null != d1) {
   day = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
  }
  return day;
 }

14. Add year in Java.util.Date

In this section, you learn about how to add years in a Java Date.

/**
  * This method is used get the date by adding year in
  * 
  * @param date
  * @param year
  * @return
  */
 public static Date getDateByAddingDay(Date date, int days) {
  Date uDate = null;
  try {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.add(Calendar.DATE, days);
   uDate = cal.getTime();
  } catch (Exception e) {
   logger.warn(e.getMessage());
  }
  return uDate;
 }

15. Add months in java.util.Date()

How to add month in Java Date and return a formated java Date.

/**
  * This method is used get the date by adding year in
  * 
  * @param date
  * @param year
  * @return
  */
 public static Date getDateByAddingMonths(Date date, int months) {
  Date uDate = null;
  try {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.add(Calendar.MONTH, months);
   uDate = cal.getTime();
  } catch (Exception e) {
   logger.warn(e.getMessage());
  }
  return uDate;
 }

16. Reference

You can visit Oracle Java site for more details.

Thanks for visiting this post for learning: Java date to string, string to date Java, how to add month in date, how to add the year in Date, different java date formate examples program. You can also visit Core Java Tutorial Listing page for more articles on Core Java examples tips and techniques.

Your comments are welcome and write your question for any function on Java date formate. happy Learning! 🙂


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *