Date From Timestamp in Long format

Generally, the dates are stored in long timestamp format in the database.
This simple class can convert the timestamp date to real date format.

package com.kushal.util;
import java.util.Date;
public class DateFromLong {

	public static void main(String ags [])
	{
		long dateInLongFormat=1212499200000L;
		Date date=new Date(dateInLongFormat);

		System.out.println(date);

	}

}

Here is the sample output for the long date give above:

Tue Jun 03 08:20:00 CDT 2008

How to calculate age in Java from birthdate?

Playing around with dates is tricky and can sometimes make you use your head, specially with the boundary conditions. In this tutorial, I am presenting a code that can take any birth date as the input and then calculates what is his / her age now.

Here is the algorithm:

  • Subtract birth year from current year.
  • Check if birth month is greater than current month (condition 1)
  • If birth month is same, check if birth day of the month is latter than the current day of the month (condition 2)
  • If condition 1 or condition 2 is satisfied, subtract 1 year from the difference calculated in step 1.
  • This value is the correct age of the individual.

Having said that, here is the Java implementation of this algorithm.

package com.kushal.utils.date;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 2009-10-13
 *
 * Takes any birth date as input
 * Calculates the current age
 */
import java.util.GregorianCalendar;
import java.util.Calendar;

public class AgeCalculation {

/**
* Month Representations
*/
static final int JAN = 0;
static final int FEB = 1;
static final int MAR = 2;
static final int APR = 3;
static final int MAY = 4;
static final int JUN = 5;
static final int JUL = 6;
static final int AUG = 7;
static final int SEP = 8;
static final int OCT = 9;
static final int NOV = 10;
static final int DEC = 11;

public static void main(String[] args) {
System.out.println("Born In 1982-JUL-11. Current Age: "
+ calculateMyAge(1982, JUL, 11));
System.out.println("Born In 1957-DEC-09. Current Age: "
+ calculateMyAge(1957, DEC, 9));
}

/**
*
* @param year --> Birth Year
* @param month --> Birth Month
* @param day --> Birth Day
* @return --> Calculated Age
*/
private static int calculateMyAge(int year, int month, int day) {
Calendar birthCal = new GregorianCalendar(year, month, day);

Calendar nowCal = new GregorianCalendar();

int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
.get(Calendar.MONTH);

boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) == nowCal
.get(Calendar.MONTH)
&& birthCal.get(Calendar.DAY_OF_MONTH) > nowCal
.get(Calendar.DAY_OF_MONTH);

if (isMonthGreater || isMonthSameButDayGreater) {
age=age-1;
}
return age;
}
/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/
}

Here is the output of the program above:

Born In 1982-JUL-11. Current Age: 27
Born In 1957-DEC-09. Current Age: 51

Calculating The Difference Between Two Dates In Terms of Months

The following programs show how to calculate the difference between two dates in terms of months

package com.kushal.util;

/**
 * @(#)KpCalendar.java
 * @author Kushal Paudyal
 * @version 1.00 2007/4/18
 * www.sanjaal.com/java
 * www.icodejava.com
 */

import java.util.*;

public class KPCalendar {

	/**Default Constructor**/
	public KPCalendar() {
	}

	public double monthDifference(String calString1, String calString2)
	{
		double difference =0;

		try{
			Calendar cal1=new GregorianCalendar();
			Date time1=new Date(calString1);

			cal1.setTime(time1);

			Calendar cal2=new GregorianCalendar();
			Date time2=new Date(calString2);
			cal2.setTime(time2);

			long time1Millis=cal1.getTimeInMillis();
			long time2Millis= cal2.getTimeInMillis();

			double d1=((double)time1Millis)/(1000*60*60*24);
			double d2=((double)time2Millis)/(1000*60*60*24);
			System.out.println(d1);
			System.out.println(d2);

			difference=Math.round(Math.abs((d1-d2)/30));
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Error Occurred");
		}
		finally{
			System.out.println(difference);
			return difference;
		}
	}

	/** Testing for the functionality of the method **/
	public static void main(String args [])
	{
		KPCalendar util=new KPCalendar();
		util.monthDifference("04/01/2007","08/5/2007");
	}
}