Thursday, June 25, 2009

How to Compare Dates


Calendar cal1 = new GregorianCalendar(2007, Calendar.SEPTEMBER, 1);
Calendar cal2 = new GregorianCalendar(2007, Calendar.SEPTEMBER, 15);

// Determine which is earlier
boolean b = cal1.after(cal2); // false
b = cal1.before(cal2); // true

// Get difference in milliseconds
long diffMillis = cal2.getTimeInMillis()-cal1.getTimeInMillis(); //1209600000

How to Create a Date Object


Calendar cal = new GregorianCalendar(2007, Calendar.SEPTEMBER, 1);
Date date = cal.getTime(); // Sat Sep 01 00:00:00 PDT 2007

How to Get the Current Date


Calendar cal = new GregorianCalendar();

// Get the components of the date
int era = cal.get(Calendar.ERA); // 1
int year = cal.get(Calendar.YEAR); // 2009
int month = cal.get(Calendar.MONTH); // 0=Jan, 1=Feb, ...
int day = cal.get(Calendar.DAY_OF_MONTH); // 25
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday, 2=Monday, ...

How to Get the Current Time in Another Time Zone


// Get the current time in London
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("London"));

int hour12 = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int am = cal.get(Calendar.AM_PM);

// Get the current hour-of-day at GMT
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
int hour24 = cal.get(Calendar.HOUR_OF_DAY);

How to Get the Current Time


Calendar cal = new GregorianCalendar();

// Get the components of the time
int hour12 = cal.get(Calendar.HOUR);
int hour24 = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millisecond = cal.get(Calendar.MILLISECOND);
int ampm = cal.get(Calendar.AM_PM);

How to Sort an Array


String[] strArray = new String[] {"x", "y", "Z"};
Arrays.sort(strArray);
// [Z, x, y]

How to Use Sorted Map


Keys in the TreeMap will automatically be sorted.

Map map = new TreeMap();
map.put("a", new Integer(1));
map.put("c", new Integer(3));
map.put("b", new Integer(2));
// [a=1, b=2, c=3]
 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez