Monday, August 10, 2009

Convert Date in to Active Directory (AD) date / datetime format

It has always bugged me whenever I delt with converting the date to Active directory date formats. Java's long date is not same as AD, As both of the applications start date are different.

Here is some sample code i have been using for long time now.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.TestCase;


/**
* @author Dilip Nimse
*
*/
public class ADDateFunctions extends TestCase {
private static final long _TIME_DIFFERENCE = 0xa9735dcc400L;
private static final long _NANO_SECONDSPER_MILLI = 10000L;
/**
* @param name
*/
public ADDateFunctions(String name) {
super(name);
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}


/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
private long convertDateToLong(Date date)
{
long longDate = date.getTime();
long l = longDate + _TIME_DIFFERENCE;
return l * _NANO_SECONDSPER_MILLI;
}
private Date convertLongToDate(long longDate)
{
long l = longDate / _NANO_SECONDSPER_MILLI;
long militime = l - _TIME_DIFFERENCE;
return new Date(militime);
}
private boolean isNoExpireDS(String s)
{
boolean flag = false;
if(s == null)
{
flag = true;
} else
{
s = s.trim();
Long long1 = new Long(1L);
try
{
long1 = Long.decode(s);
}
catch(NumberFormatException numberformatexception) { }
flag = flag long1.longValue() == 0L;
flag = flag s.length() == 0;
}
return flag;
}


public String datetoAD(String s, String dateFormat)
{
SimpleDateFormat simpledateformat = new SimpleDateFormat(dateFormat);
long l = 0L;
if(isNoExpireDS(s))
l = 0x7fffffffffffffffL;
else
try
{
Date date = simpledateformat.parse(s);
l = convertDateToLong(date);
}
catch(ParseException parseexception) { }
return new String(Long.toString(l));
}
public String adDatetoDate(String s, String dateFormat)
{
SimpleDateFormat simpledateformat = new SimpleDateFormat(dateFormat);
long l = Long.parseLong(s);
Date date = convertLongToDate(l);
return new String(simpledateformat.format(date));
}
public void testGetADDate(){
System.out.println("Lets test the AD Date Conversions") ;
String s = new String("05/15/2009");
System.out.println("Active Directory Date Format for " + s + " is : " + datetoAD(s, "MM/dd/yyyy"));
String s1 = datetoAD(s, "MM/dd/yyyy");
System.out.println("Active Directory Date " +s1 + " converted back to Calendar date is : " + adDatetoDate(s1, "MM/dd/yyyy"));
}

}

No comments:

Post a Comment