Java Date Utility class example

Java Date Utility class example

Working with Java or any other language using Date is obviously mandatory. First thing we do whenever we do start working on project created these mandatory utility class which can be use through out the project. Below is handy java date utility class which can be use in any project:

  • JavaDateUtility.java:
package com.vzw.mss.mf.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.Months;

public class JavaDateUtility {
	
	public static final long APPROX_MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
	public static final DateFormat DVS_DATE_FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
	public static final String DATE_FORMAT_MMDDYY_HH24MMSS = "MM-dd-yy HH:mm:ss";
	public static final String  DATE_FORMAT_yyyy_MM_ddT = "yyyy-MM-dd'T'HH:mm:ssXXX";
	public static final String DATE_FORMAT_MMDDYYYY = "MM/dd/yyyy";
	public static final String DATE_FORMAT_MMMDD_YYYY = "MMM d,yyyy";
	public static final String DATE_FORMAT_MMMd_yyyy = "MMM d";	
	public static final String DATE_FORMAT_MMDDYY = "MM/dd/yy";
	public static final String DATE_FORMAT_YYMMDD = "yyMMdd";
	public static final String DATE_FORMAT_MMMDD = "MMM d";
	public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";
	public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
	public static final String TIMESTAMP_GMT = "GMT";
	public static final String TIMESTAMP_UTC = "UTC";
	public static final String DATE_FORMAT_YYYY = "YYYY";
	public static final String DATE_FORMAT_YY = "yy";
	public static final String XML_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'hh:mm:ss.sss'-'hh:mm";
	public static final String DATE_FORMAT_MMMD = "MMM d";
	public static final String DATE_FORMAT_H_M_A = "h:mm a";
	public static final String DATA_METER_DATE_FORMAT = "MM/dd/yyyy hh:mm a";
	public static final String DATE_FORMAT_MMDDYY_HHMMSS_AMPM = "MM-dd-yy hh:mm:ss a";
	public static final String DATE_FORMAT_MMDDYY_HHMMSS_Z="yyyy-MM-dd'T'HH:mm:ssZ";
	public static final String ATG_GETFEED_DATE_FORMAT = "MM/dd/yyyy";
	public static final String DATE_FORMAT_MMDD = "MM/dd";
	public static final String DATE_FORMAT_MMDDYY_HHMMSS = "yyyy-MM-dd hh:mm:ss";
	
	public static void main(String[] args) {
		
	}

	public static Date convertStrToDate(String date) {
		return convertStrToDateFormat(date, DATE_FORMAT_MMDDYYYY);
	}
	
	public static Date convertStrToDateFormat(String date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date returnDate = null;
		try {
			returnDate = StringUtils.isNotBlank(date) ? sdf.parse(date) : null;
		} catch (ParseException e) {			
			e.printStackTrace();
		}
		return returnDate;
	}

	public static long getDaysDiffBetweenDates(Date date1, Date date2) {
		long daysInBetween = 0;
		try {
			long timeDifference = date2.getTime() - date1.getTime();
			daysInBetween = timeDifference / (24 * 60 * 60 * 1000);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return daysInBetween;

	}

	public static int daysBetween(String endDate) {
		int daysBetween = 0;

		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);

		Date dEnd = null;

		try {
			dEnd = format.parse(endDate);

			DateTime dt1 = new DateTime();
			DateTime dt2 = new DateTime(dEnd);

			daysBetween = Days.daysBetween(dt1, dt2).getDays() + 1;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return daysBetween;
	}
	
	public static int monthsBetween(String endDate) {
		int monthsBetween = 0;

		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);

		Date dEnd = null;

		try {
			// dStart = format.parse(dateStart);
			dEnd = format.parse(endDate);

			DateTime dt1 = new DateTime();
			DateTime dt2 = new DateTime(dEnd);

			monthsBetween	= Months.monthsBetween(dt2, dt1).getMonths();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return monthsBetween;
	}
	
	public static String getStarDateToEndDateByEndDate(String endDateStr){
	    
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		SimpleDateFormat formatter2 = new SimpleDateFormat(DATE_FORMAT_MMMd_yyyy);
		try{
			Date endDate= formatter.parse(endDateStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate);
			cal.add(Calendar.MONTH, -1);
			cal.add(Calendar.DATE, 1);
			Date startDate = cal.getTime();
			String startDateFormat = formatter2.format(startDate);
			String endDateFormat= formatter2.format(endDate);
			return startDateFormat+" - "+endDateFormat;
		}catch(ParseException e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getStarDateToEndDateByEndDateForDataHistory(String endDateStr){
	    
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		SimpleDateFormat formatter2 = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);
		try{
			Date endDate= formatter.parse(endDateStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate);
			cal.add(Calendar.MONTH, -1);
			cal.add(Calendar.DATE, 1);
			Date startDate = cal.getTime();
			String startDateFormat = formatter2.format(startDate);
			String endDateFormat= formatter2.format(endDate);
			return startDateFormat+" - "+endDateFormat;
		}catch(ParseException e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getStarDateToEndDateByEndDateMMMDD(String endDateStr){
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		SimpleDateFormat formatter2 = new SimpleDateFormat(DATE_FORMAT_MMMDD);
		try{
			Date endDate= formatter.parse(endDateStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate);
			cal.add(Calendar.MONTH, -1);
			cal.add(Calendar.DATE, 1);
			Date startDate = cal.getTime();
			String startDateFormat = formatter2.format(startDate);
			String endDateFormat= formatter2.format(endDate);
			return startDateFormat+" - "+endDateFormat;
		}catch(ParseException e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static int daysBetweenWithStartOfDay(String endDate) {
		int daysBetween = 0;

		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);

		Date dEnd = null;

		try {
			
			dEnd = format.parse(endDate);

			DateTime dt1 = new DateTime();
			DateTime dt2 = new DateTime(dEnd);

			daysBetween = Days.daysBetween(dt1.withTimeAtStartOfDay(), dt2.withTimeAtStartOfDay()).getDays();
			
		} catch (Exception e) {
			e.printStackTrace();		    
		}
		return daysBetween;		
	}

	public static Calendar convertStrToCalendar(String date) {

		DateFormat df = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		Calendar cal = Calendar.getInstance();
		try {
			if (StringUtils.isNotEmpty(date)) {
				cal.setTime(df.parse(date));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return cal;
	}

	public static Calendar convertStrToCalendar(String date, String format) {

		DateFormat df = new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();
		try {
			if (StringUtils.isNotEmpty(date)) {
				cal.setTime(df.parse(date));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return cal;
	}
	
	public static Calendar convertStrToCal(String date, String format){
		try {
		DateFormat df = new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();
		if (StringUtils.isNotEmpty(date)) {
			cal.setTime(df.parse(date));
		}
		return cal;
	} catch (Exception e) {
		return null;
		
	}
		
	}
	
	public static boolean equalsDate(Calendar date1, Calendar date2) {
		try {
			if (date1 != null && date2 != null) {
				if (date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)
						&& date1.get(Calendar.DAY_OF_MONTH) == date2.get(Calendar.DAY_OF_MONTH)
						&& date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR)) {
					return true;

				} else {
					return false;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean isSameDate(Date d1, Date d2) {
		Calendar date1 = Calendar.getInstance();
		Calendar date2 = Calendar.getInstance();
		date1.setTime(d1);
		date2.setTime(d2);
		try {
			if (date1 != null && date2 != null) {
				if (date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)
						&& date1.get(Calendar.DAY_OF_MONTH) == date2.get(Calendar.DAY_OF_MONTH)
						&& date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR)) {
					return true;

				} else {
					return false;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String formatYYtoYYYY(String year) throws ParseException {
		SimpleDateFormat inputYearFormatter = new SimpleDateFormat(DATE_FORMAT_YY);
		SimpleDateFormat outputYearFormatter = new SimpleDateFormat(DATE_FORMAT_YYYY);
		String outputYear = null;
		
		try {
			if (StringUtils.isNotEmpty(year)) {
				Date inputDate = inputYearFormatter.parse(year);
				outputYear = outputYearFormatter.format(inputDate);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return outputYear;
	}

	public static long getCurrentTimeGMT() {
		return Calendar.getInstance(TimeZone.getTimeZone(TIMESTAMP_GMT)).getTimeInMillis();
	}

	public static Date formatDate(String dateStr) {
		SimpleDateFormat originalFormatter = new SimpleDateFormat(DATE_FORMAT_YYMMDD);
		ParsePosition pos = new ParsePosition(0);
		java.util.Date dateFromString = originalFormatter.parse(dateStr, pos);
		return dateFromString;
	}

	public static String formatDateMDYY(String date) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
			Date dt = format.parse(date);
			return format.format(dt);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getXMLTimeStampFormat(){
		Date d = Calendar.getInstance().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat(XML_TIMESTAMP_FORMAT); 
		return sdf.format(d);			
	}	

	public static String format(String date) {
		SimpleDateFormat originalFormatter = new SimpleDateFormat(DATE_FORMAT_YYMMDD);
		SimpleDateFormat newFormatter = new SimpleDateFormat(DATE_FORMAT_MMDDYY);
		ParsePosition pos = new ParsePosition(0);
		java.util.Date dateFromString = originalFormatter.parse(date, pos);
		String dateStringInNewFormat = newFormatter.format(dateFromString);
		return dateStringInNewFormat;
	}

	public static ArrayList<String> getCalendarDropDown(String paymentDays, String billingSystem,
			String billSysTimeZoneMapping) {
		ArrayList<String> dateList = new ArrayList<String>();
		Calendar myCalendar = Calendar.getInstance();
		SimpleDateFormat formatDate = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		String timeZone = null;
		try {
			timeZone = getTimeZone(billSysTimeZoneMapping, billingSystem);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (StringUtils.isNotBlank(timeZone)) {
			formatDate.setTimeZone(TimeZone.getTimeZone(timeZone));
		}

		Date currDate = myCalendar.getTime();
		String currdate = "";
		currdate = formatDate.format(currDate);
		int days = Integer.parseInt(paymentDays);

		for (int i = 0; i < days; i++) {

			currDate = myCalendar.getTime();
			currdate = formatDate.format(currDate);
			dateList.add(currdate.toString());
			myCalendar.add(Calendar.DATE, 1);

		}
		return dateList;
	}
	
	public static ArrayList<String> getDaysofCurrentMonth() {
		ArrayList<String> dateList = new ArrayList<String>();
		Calendar c = Calendar.getInstance();
		int monthMaxDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		
		for(int i=1; i<=monthMaxDays; i++) {
			dateList.add(String.valueOf(i));
		}
		return dateList;
	}

	public static String getTimeZone(String billSysTimeZoneMapping, String visionBillingSystem) {
		String[] billSysTimeZoneArray = null;
		String[] billSystemArray = null;
		if (StringUtils.isNotBlank(billSysTimeZoneMapping)) {
			billSysTimeZoneArray = billSysTimeZoneMapping.split(";;");
			if (billSysTimeZoneArray != null && billSysTimeZoneArray.length > 0) {
				for (String billSystemTZ : billSysTimeZoneArray) {
					if (StringUtils.isNotBlank(billSystemTZ)) {
						billSystemArray = billSystemTZ.split(":");
						if (StringUtils.equals(billSystemArray[0], visionBillingSystem)) {
							return billSystemArray[1];
						}
					}
				}

			}
		}
		return null;
	}

	public static String formatyyMMdd(String date) {
		SimpleDateFormat originalFormatter = new SimpleDateFormat(DATE_FORMAT_MMDDYY);
		SimpleDateFormat newFormatter = new SimpleDateFormat(DATE_FORMAT_YYMMDD);
		ParsePosition pos = new ParsePosition(0);
		java.util.Date dateFromString = originalFormatter.parse(date, pos);
		String dateStringInNewFormat = newFormatter.format(dateFromString);
		return dateStringInNewFormat;
	}


	public static final Timestamp getCurrentDateBeginTime() {
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone(TIMESTAMP_GMT));
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
		cal.set(Calendar.MINUTE, 0); // set minute in hour
		cal.set(Calendar.SECOND, 0); // set second in minute

		return new Timestamp(cal.getTimeInMillis());
	}

	public static final Timestamp getCurrentDateEndTime() {
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone(TIMESTAMP_GMT));
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 23); // set hour to midnight
		cal.set(Calendar.MINUTE, 59); // set minute in hour
		cal.set(Calendar.SECOND, 59); // set second in minute

		return new Timestamp(cal.getTimeInMillis());
	} 

	public static String formattoMMMYY(Calendar convertStrToCalendar) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMMDD);
		return format.format(convertStrToCalendar.getTime());
	}

	public static String formattoMMMDDYY(Calendar convertStrToCalendar) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);
		return format.format(convertStrToCalendar.getTime());
	}
	
	public static String formatDateMDYY(Calendar convertStrToCalendar) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		return format.format(convertStrToCalendar.getTime());
	}
	
	public static long daysBetween(Date sDate, Date eDate) {
		Calendar startDate = Calendar.getInstance();
		Calendar endDate = Calendar.getInstance();
		startDate.setTime(sDate);
		endDate.setTime(eDate);
		Calendar date = (Calendar) startDate.clone();
		long daysBetween = 0;
		while (date.before(endDate)) {
			date.add(Calendar.DAY_OF_MONTH, 1);
			daysBetween++;
		}
		return daysBetween;
	}
	
	public static long daysBetween(Calendar sDate, Calendar eDate) {
		Calendar date = (Calendar) sDate.clone();
		long daysBetween = 0;
		while (date.before(eDate)) {
			date.add(Calendar.DAY_OF_MONTH, 1);
			daysBetween++;
		}
		return daysBetween;
	}



	public static String formatDateMMMDDYYYY(String dateInString) {
		try {
			SimpleDateFormat informat = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);
			SimpleDateFormat outformat = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);
			Date date = informat.parse(dateInString);
			return outformat.format(date);
		} catch (Exception e) {
			return null;
		}
	}
	

	public static String formatPrevDateMDYY(String date) {
		try {
			
			SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);		
			Date dt = format.parse(date);
			Calendar cal = Calendar.getInstance();
			cal.setTime(dt);
			cal.add(Calendar.MONTH, -1);
			cal.add(Calendar.DATE, 1);

			return format.format(cal.getTime());
		} catch (Exception e) {
			return null;
		}
	}

	public static String getCurrentYearMonth() {

		// Getting Current Month and Year
		Calendar calendar = Calendar.getInstance();
		String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
		if (month.length() == 1) {
			month = 0 + month;
		}
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		
		return year + "-" + month;
	}
	
	public static String getYearMonth(Date date) {

		// Getting Current Month and Year
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
		if (month.length() == 1) {
			month = 0 + month;
		}
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		return year + "-" + month;
	}

	public static String getTodayFormatDDMMYYYY() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		return sdf.format(now.getTime());
	}

	public static String getCurrentTimeHHMMSS() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(now.getTime());
	}
	
	public static String formatUsageDateTime(Calendar cal) {
		
		 final String USAGE_DISPLAY_DATE_FORMAT = "M/d/yy h:mma";
		 
		SimpleDateFormat usageDisplayFormat = new SimpleDateFormat(USAGE_DISPLAY_DATE_FORMAT);	
		String dateTime = usageDisplayFormat.format(cal.getTime());
		return dateTime;					
	}

	public static int getDayOfTheMonth (String date)
	{
		Calendar calendar = convertStrToCalendar(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
		
	}
	
	public static int getDayOfTheMonth (String date,String format)
	{
		Calendar calendar = convertStrToCalendar(date, format);
		
		return calendar.get(Calendar.DAY_OF_MONTH);
		
	}
	
	
	public static String getDayOfMonthSuffix(final int n) {
	    if (n >= 11 && n <= 20) {
	        return String.valueOf(n).concat("th");
	    }
	    switch (n % 10) {
	        case 1:  return String.valueOf(n).concat("st");
	        case 2:  return String.valueOf(n).concat("nd");
	        case 3:  return String.valueOf(n).concat("rd");
	        default: return String.valueOf(n).concat("th");
	    }
	}


	public static String getXMLGregorianCalendarNow() throws Exception {
		XMLGregorianCalendar now = null;
		GregorianCalendar gregorianCalendar = new GregorianCalendar();
		DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
		now = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
		return now.toString();
	}
	
	/**
	 * @param calendar
	 * @return date in  "MMM d".
	 * example: Mar 29.
	 */
	public static String formattoMMMD(Calendar calendar) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMMD);
		return format.format(calendar.getTime());
	}
	
	
	/**
	 * @param calendar
	 * @return date in  "h:m a".
	 *  example: 1:25 AM.
	 */	
	public static String formattoHMA(Calendar calendar) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_H_M_A);
		return format.format(calendar.getTime());
	}
	
	public static String getMonth(Date date){
		Format formatter = new SimpleDateFormat("MMM"); 
	    return formatter.format(date);
	}
	
	/**
	 * This method gets the current time and convert into GMT time zone in the format MM-dd-yy hh:mm:ss a z
	 * Example: 04-21-16 04:30:00 PM GMT
	 * @return
	 */
	public static String getCurrentDateTimeInGMT() {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MMDDYY_HHMMSS_AMPM); // 04-21-16 04:30:00 PM
		Calendar calendar = Calendar.getInstance();
		
        TimeZone currentTimeZone = calendar.getTimeZone();
        TimeZone GMTTimeZone = TimeZone.getTimeZone("GMT");

        calendar.setTimeZone(currentTimeZone);
        
        // Subtract the difference of milliseconds between two time zones
        calendar.add(Calendar.MILLISECOND, currentTimeZone.getRawOffset() * -1);
        
        // Daylight savings adjustment for current time
        if (currentTimeZone.inDaylightTime(calendar.getTime())) {
            calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
        }

        calendar.add(Calendar.MILLISECOND, GMTTimeZone.getRawOffset());
        
        // Daylight savings adjustment for GMT converted time
        if (GMTTimeZone.inDaylightTime(calendar.getTime())) {
            calendar.add(Calendar.MILLISECOND, GMTTimeZone.getDSTSavings());
        }

		return format.format(calendar.getTime()) + " GMT";
	}	
	
	
	public static long getCurrentTimeUTC() {
		return Calendar.getInstance(TimeZone.getTimeZone(TIMESTAMP_UTC)).getTimeInMillis();
	}
	
	public static String getTimeDiffInHoursBetweenDates(String startTime, String endTime) {		
		String duration = null;
		long diffHours = 0;
		try {
			Date date1 = convertStrToDateFormat(startTime, "yyyy-MM-dd HH:mm:ss");
			Date date2 = convertStrToDateFormat(endTime,"yyyy-MM-dd HH:mm:ss");

			long timeDifference = date2.getTime() - date1.getTime();

			diffHours = (timeDifference/1000)/60;
			duration = String.valueOf(diffHours);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return duration;

	} 

	public static long  getTimeDiffBetweenTwoDates(String startDateTime, String endDateTime){
		
		long seconds =0l;
		
		try {
			
			DateTimeZone UTCDateTimeZone = DateTimeZone.forID("UTC");
			
			DateTime currentTimeGMT = new DateTime(UTCDateTimeZone);
			
		    Date endDate = convertStrToDateFormat(endDateTime,"yyyy-MM-dd HH:mm:ss");
		    
			Calendar calendar = Calendar.getInstance();
			
			calendar.setTime(endDate);

			int month = calendar.get(Calendar.MONTH)+1;
			
			DateTimeZone localTimeZone = DateTimeZone.UTC;
			 
			DateTime utcTime = new DateTime( calendar.get(Calendar.YEAR), month, calendar.get(Calendar.DATE), calendar.get(Calendar.HOUR_OF_DAY), 
					calendar.get(Calendar.MINUTE),calendar.get(Calendar.SECOND),
			        DateTimeZone.UTC);
			
			
			DateTime gmtTimeEndSession = utcTime.withZone(localTimeZone);
			
			long timeDifference = gmtTimeEndSession.getMillis() - currentTimeGMT.getMillis();
			 seconds = (timeDifference/1000);
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return 0l;
		}
		return seconds;

	}
	
	public static String getCurrentDateFormatted(){
		try {
			Calendar cal = Calendar.getInstance();
	        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
	        return sdf.format(cal.getTime());
		} catch (Exception e) {
			return null;
		}
	}
	
	
	
	public static String formatDateMMMDD(String dateInString) {
		try {
			SimpleDateFormat informat = new SimpleDateFormat(DATE_FORMAT_MMDD);
			SimpleDateFormat outformat = new SimpleDateFormat(DATE_FORMAT_MMMDD);
			Date date = informat.parse(dateInString);
			return outformat.format(date);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static Calendar convertCalendar(Calendar calendar, final TimeZone timeZone) {
	    try {
			Calendar ret = new GregorianCalendar(timeZone);
		    ret.setTimeInMillis(calendar.getTimeInMillis() +
		            timeZone.getOffset(calendar.getTimeInMillis()) -
		            TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
		    ret.getTime();
		    return ret;
	    }
	    catch(Exception e) {
	    	return null;
	    }
	}
	
	public static String formatDateMMDDYYYYtoMMMDD_YYYY(String dateInString) {
		try {
			SimpleDateFormat informat = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
			SimpleDateFormat outformat = new SimpleDateFormat(DATE_FORMAT_MMMDD_YYYY);
			Date date = informat.parse(dateInString);
			return outformat.format(date);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static XMLGregorianCalendar getXMLGregorianCalendar(){
	//	Date date=null;
		XMLGregorianCalendar xmlGregorianCalendar;
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			//date = df.parse(new Date().toString());
			GregorianCalendar cal = new GregorianCalendar();
			cal.setTime(new Date());		
			xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), (new Date()).getHours(),(new Date()).getMinutes(),(new Date()).getSeconds(),DatatypeConstants.FIELD_UNDEFINED, cal.getTimeZone().LONG).normalize();
		} catch (DatatypeConfigurationException e) {			
			e.printStackTrace();
			return null;
		} 	
		return xmlGregorianCalendar;
	}
	
	public static String addDaysMonthYearToDate(String date, int partOfDate, int addNumber) {
		
		String returnDate = null;
		try {
			Calendar cal = convertStrToCalendar(date);
			
			cal.add(partOfDate, addNumber);
			
			returnDate = formatDateMDYY(cal);
		}
		catch(Exception ex) {
			ex.printStackTrace();
			return null;
		}
		
		return returnDate;
	}
	
	public static String getDateByDateRange(int dateRange){
		Date date = new Date();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");	 
		Date today = new Date();
		Calendar cal = new GregorianCalendar();
		cal.setTime(today);
		if(dateRange == 30){
			cal.add(Calendar.DAY_OF_MONTH, -30);
			date = cal.getTime();
		}
		else if(dateRange == 60){
			cal.add(Calendar.DAY_OF_MONTH, -60);
			date = cal.getTime();
		}
		else if(dateRange == 90){
			cal.add(Calendar.DAY_OF_MONTH, -90);
			date = cal.getTime();
		}
		else if(dateRange == 180){
			cal.add(Calendar.DAY_OF_MONTH, -180);
			date = cal.getTime();
		}
		return sdf.format(date) ;
	}
	
	public static String getTodayFormatYYYYMMDD() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYYMMDD);
		return sdf.format(now.getTime());
	}
	
	public static String getTodayFormatYYYY_MM_DD() {
		Calendar now = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD);
		return sdf.format(now.getTime());
	}
	
	public static Calendar convertStrToCalendarHHMMSS(String date) {

		DateFormat df = new SimpleDateFormat(DATE_FORMAT_MMDDYY_HHMMSS);
		Calendar cal = Calendar.getInstance();
		try {
			if (StringUtils.isNotEmpty(date)) {
				cal.setTime(df.parse(date));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return cal;
	}
	
	public static String getFormatFromMM_DD_YYYYToMMMDD(String dateIn){
		DateFormat df = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		DateFormat df2 = new SimpleDateFormat(DATE_FORMAT_MMMDD);
		try {
			Date d= df.parse(dateIn);
			String dateOut= df2.format(d);
			return dateOut;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static long getCurrentESTDate() {
		return Calendar.getInstance(TimeZone.getTimeZone("EST")).getTime().getTime();
	}


	public static String addThreeDays(String dateIn) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_MMDDYYYY);
		SimpleDateFormat outformat = new SimpleDateFormat(DATE_FORMAT_MMMDD);
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime( dateFormat.parse( dateIn ) );
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal.add( Calendar.DATE, 3 );
		String convertedDate=outformat.format(cal.getTime());  
		return convertedDate;
	}
	


}

 

Reference:

Leave a Reply

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