Archives: Date Time

Java – Date Sort Example

[code lang=”java”]import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class JavaDateSortExample {

/**
* Java Date Sort Example
* This example will sort dates objects and provide ascending order
* This class used for sorting dates using Calendar and date class
*/
public static void main(String[] args) {

// Unsorted dates which need to sort
String[] dateToSort = {"22NOV2012","02JAN2013","14OCT2011","07MAR2012"};

// Calendar is used to give date object and set date object
Calendar calenderSort = Calendar.getInstance();

// Set calendar provide us ordered and unique dates object
Set<Calendar> sortedList = new TreeSet<Calendar>();
try {

// We need to first format dates string into date object for sort
// date parse() method is used to parse date
for(String strdate : dateToSort) {
SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy");
Date dateparse = sdf.parse(strdate);
calenderSort = Calendar.getInstance();
calenderSort.setTime(dateparse);
sortedList.add(calenderSort);
System.out.println("Unsorted Date :"+dateparse);
}
// We will get date in sorted form
Iterator<Calendar> it = sortedList.iterator();
Date sortedDate = new Date();
while(it.hasNext()){
sortedDate = it.next().getTime();
System.out.println("Sorted Date :"+sortedDate);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}[/code]


Java – Convert Milliseconds to Date

[code lang=”java”]import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MillisToDate {

public static void main(String args[]) {

//Converting milliseconds to Date using java.util.Date
//current time in milliseconds
long currentDateTime = System.currentTimeMillis();

//creating Date from millisecond
Date currentDate = new Date(currentDateTime);

//printing value of Date
System.out.println("current Date: " + currentDate);

DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss");

//formatted value of current Date
System.out.println("Milliseconds to Date: " + df.format(currentDate));

//Converting milliseconds to Date using Calendar
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentDateTime);
System.out.println("Milliseconds to Date using Calendar:" + df.format(cal.getTime()));

//copying one Date’s value into another Date in Java
Date now = new Date();
Date copiedDate = new Date(now.getTime());

System.out.println("original Date: " + df.format(now));
System.out.println("copied Date: " + df.format(copiedDate));
}

}[/code]
Output:

current Date: Wed Feb 29 01:58:46 VET 2012
Milliseconds to Date: 29:02:12:01:58:46
Milliseconds to Date using Calendar:29:02:12:01:58:46
original Date: 29:02:12:01:58:46
copied Date: 29:02:12:01:58:46