Difference between java dates

DateDiff is an useful java class to calculate difference between two java.util.Date and getting the result represented by days, hours, minutes. See the code above:








import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
public class DateDiff {

private Date d1;
private Date d2;
private final int MSEC_PER_SECOND = 1000;
private final int MSEC_PER_MINUTE = 60*1000;
private final int MSEC_PER_HOUR = 60*60*1000;
private final int MSEC_PER_DAY = 24*60*60*1000;

private long days;
private long hours;
private long minutes;
private long seconds;

public DateDiff() {
d1 = new Date();
d2 = new Date();
compute();
}
public DateDiff(Date d1, Date d2) {
this.d1 = d1;
this.d2 = d2;
compute();
}

/* GETTERS AND SETTERS METHODS */
public Date getD1() {
return d1;
}

public void setD1(Date d1) {
this.d1 = d1;
compute();
}

public Date getD2() {
return d2;
}

public void setD2(Date d2) {
this.d2 = d2;
compute();
}

public long getDays() {
return days;
}

public long getHours() {
return hours;
}

public long getMinutes() {
return minutes;
}

public long getSeconds() {
return seconds;
}


/* BUSINESS METHODS */

public long getDiffInMillisecs() {
return d2.getTime() - d1.getTime();
}

public long getDiffInSeconds() {
return ( d2.getTime() - d1.getTime()) / MSEC_PER_SECOND;
}

public long getDiffInMinutes() {
return ( d2.getTime() - d1.getTime()) / MSEC_PER_MINUTE;
}

public long getDiffInHours() {
return ( d2.getTime() - d1.getTime()) / MSEC_PER_HOUR;
}

public long getDiffInDays() {
return ( d2.getTime() - d1.getTime()) / MSEC_PER_DAY;
}

private void compute() {
days = getDiffInDays();
hours = getDiffInHours() - (getDiffInDays() * 24);
minutes = getDiffInMinutes() - (getDiffInHours() * 60);
seconds = getDiffInSeconds() - (getDiffInMinutes() * 60);
}

public String toString () {
return days+" days, "+hours+" hours, "+minutes+" minutes, "+seconds+" seconds ";
}

public int getWorkingDays() {
Calendar c = Calendar.getInstance();
c.setTime(d1);
int counter = 0;
for ( ; !c.getTime().after(d2) ; c.add(Calendar.DATE, 1) ) {
if (c.get(Calendar.DAY_OF_WEEK)!=Calendar.SATURDAY && c.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY )
counter++;
}
return counter;
}




------------------------------------------------------------------------------------------

EXAMPLE OF USAGE:

import java.util.Date;

public class Test {

public static void main (String args[]) {

Date d1 = new Date(2008, 10, 1, 10, 30, 00); // 06/10/2008 10:30:00
Date d2 = new Date(2008, 10, 10, 11, 10, 20); // 22/10/2008 11:10:20
DateDiff diff = new DateDiff( d1 , d2 );
System.out.println(diff);

}

}

Javascript simple text clock


var DaysOfWeek = new Array( "Domenica","Lunedì","Martedì",
"Mercoledì","Giovedì",
"Venerdì","Sabato");


var MonthsOfYear = new Array( "Gennaio","Febbraio","Marzo",
"Aprile","Maggio","Giugno",
"Luglio","Agosto","Settembre",
"Ottobre","Novembre","Dicembre");

function show_clock() {
var Digital = new Date();
var day = Digital.getDay();
var mday = Digital.getDate();
var month = Digital.getMonth();
var year = Digital.getFullYear();
var hours = Digital.getHours();
var minutes = Digital.getMinutes();
var seconds = Digital.getSeconds();
if (minutes <= 9) { minutes = "0"+minutes; }
if (seconds <= 9) { seconds = "0"+seconds; }
myclock = '';
myclock += "Oggi "+DaysOfWeek[day]+", "+mday+' '+MonthsOfYear[month]+" "+year;
myclock +=" , ";
myclock += "ore "+hours+':'+minutes+':'+seconds;
document.getElementById("dataora").innerHTML = myclock;
setTimeout("show_clock()",1000);
}


In your web page:
  1. call showClock() javascript function when loading page:
    body onload="javascript: showClock();"
  2. create a div with id = "dataOra". Its innerHTML will be updated each second, as specified in
    setTimeout ( 1000 millisec == 1 sec. ).

java.util.Date and java.util.Calendar

  1. Getting last day of a month:
    //The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0;
    int month = 1; //So 1 wil l be FEBRUARY
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
    java.util.Date maxDateInMonth = c.getTime();

  2. Formatting date as String:
    java.util.Date myDate = new java.util.Date();
    java.text.SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    //For others patterns click here
    String formattedDate = null;
    try {
    formattedDate = sdf.format(myDate);
    } catch (Exception e) {
    e.printStackTrace();
    }


  3. Change String format of a date:
    String strDate = "2008-10-11";
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
    String converted = null;
    try {
    converted = sdf2.format( sdf1.parse(date) );
    // converted will be "10/11/2008"
    } catch (Exception e) {
    e.printStackTrace();
    }

MD5 with java

/* This code shows how to calculate MD5 hash of a String. */

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TestMD5 {

public static void main( String[] args )
throws UnsupportedEncodingException, NoSuchAlgorithmException {
System.out.println( getMD5("Hello World, md5!") );
}

protected static String getMD5(String message) {
String hash = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
hash = hex(md.digest(message.getBytes("UTF-8"))); //CP1252
}
catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
catch (UnsupportedEncodingException e) { e.printStackTrace();}
return hash;
}

protected static String getRandomMD5() {
String message = ""+Math.round((Math.random()* System.currentTimeMillis()));
return getMD5(message);
}

private static String hex(byte[] array) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <> sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toLowerCase().substring(1,3));
}
return sb.toString(); }
}