Working with Java Date and Calendar API


Working with Java Date, Calendar API

The following code tries to demonstrate main usage of Java Date, and Calendar API.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DateCalendarTest {
    public static void testSimpleDateFormat() throws ParseException {
       // If no timezone is set, it would use the default timezone.
       DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
       // String to Date
       Date date = df.parse("2011/04/16 26:65");
       df.setLenient(true); // allow string like 26:65 etc, default is true
       // Date to String
       String sre = df.format(new Date());
       // this would use the default format of the user's computer
       df = DateFormat.getDateInstance();
       // It also provides some alternative styles for dates.
       df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
       df = DateFormat.getDateInstance(DateFormat.LONG);
       df = DateFormat.getTimeInstance();
    }
    public static void testCalendar() {
       // this would create a calendar with current time and time zone.
       Calendar calendar = Calendar.getInstance();
       Date date = calendar.getTime();
       // Be aware that months start with January equal to 0, month of the
       // following time is May.
       calendar = new GregorianCalendar(2011, 04, 16);
       // A better way to create that date would be:
       calendar = new GregorianCalendar(2011, Calendar.APRIL, 16, 23, 31, 00);
       calendar.add(GregorianCalendar.DATE, 90);
       calendar.add(GregorianCalendar.MONTH, 1);
       // calculate difference between times
       System.err.println(calendar.getTime());
    }
    public static void compareDate(Calendar calendar1, Calendar calendar2) {
       long days, hours, minutes, seconds;
       long diff = calendar1.getTimeInMillis() - calendar2.getTimeInMillis();
       long millisADay = 24 * 60 * 60 * 1000;
       days = diff / millisADay;
       diff = diff - (days * millisADay);
       hours = diff / 3600;
       diff = diff - (hours * 3600);
       minutes = diff / 60;
       diff = diff - (minutes * 60);
       seconds = diff;
       System.out.println(days + " days(s) " + hours + " hour(s) " + minutes
               + " minute(s) " + seconds + " second(s)");
    }
    public static void testTimeZone() {
       // displays the ID of the current default time zone
       System.out.println(TimeZone.getDefault().getID()); // Asia/Shanghai
       // You can change system property - user.timezone to alter the default time zone.
    }
    public static void testSqlTime() {
       // convert a java.sql.timestamp to a java.util.Date
       java.sql.Timestamp t = new java.sql.Timestamp(new Date().getTime());
       // 1 Milli = 1x10^6 Nanos
       Date d = new Date(t.getTime() + (t.getNanos() / 1000000));
       DateFormat df = new SimpleDateFormat("MM/dd/yy hh:mm:ss.SSS a");
       System.out.println(df.format(d)); // Right! At least we have the millis
    }
    /**
     * This is a program to demonstrate how to group the days between startDate
     * and endDate by week
     */
    public static void runWeeklyReport(Date startDate, Date endDate) {    Calendar startCalendar = Calendar.getInstance();
       startCalendar.setTime(startDate);
       Calendar endCalendar = Calendar.getInstance();
       endCalendar.setTime(endDate);
       while (startCalendar.before(endCalendar)) {
           Date weekStartDate = startCalendar.getTime();
           int dayOfWeek = startCalendar.get(Calendar.DAY_OF_WEEK);
           if (dayOfWeek != Calendar.SUNDAY) {
              startCalendar.add(Calendar.DAY_OF_WEEK, 7 - dayOfWeek + 1);
              startCalendar.set(Calendar.HOUR, 23);
              startCalendar.set(Calendar.MINUTE, 59);
              startCalendar.set(Calendar.SECOND, 59);
           }
           if (startCalendar.before(endCalendar)) {
              Date weekEndDate = startCalendar.getTime();
              subrutine(weekStartDate, weekEndDate);
           } else {
              break;
           }
           // Go to next week
           startCalendar.add(Calendar.SECOND, 1);
       }
    }
private static void subrutine(Date weekStartDate, Date weekEndDate) {
       System.err.println(weekStartDate + ":" + weekEndDate);
    }
}
Caveat
1. Months start with January equal to 0:
new GregorianCalendar(2011, 04, 16); the month would be set to May, not April, better to use the defined constants: Calendar.JANUARY.
2. The first day of week is SUNDAY, Calendar.SUNDAY = 1.

java.sql.Date, java.sql.Time, java.sql.Timestamp are subclasses of java.util.Date.

So don't use instance variables or static instance variables to store a SimpleDateFormat - in this way, you have to synchronize its access.
Instead, the simple and safe way is to create a new SimpleDateFormat object each time - modern jvms don't have any problem allocating short lived objects.

Validation
By default SimpleDateFormat is lenient, it is tolerant to some formatting errors. It will try to figure out the date by applying some heuristics to the given text.
So the following date would be interpreted as 2011/06/10 03:05:00.
Date date = df.parse("2011/04/100 26:65:00");

If you want to strictly validate user input, set the SimpleDateFormat non-lenient by: sdf.setLenient(false);

Many methods in java.util.Date are deprecated, but it doesn't mean java.util.Date is dead. In stead, we should use java.util.Date, Calendar together, use Date objects to hold, store or communicate a date-time value. Use a Calendar object to manipulate a date-time value. Of course don't use the deprecated methods of java.util.Date.

What then is the role of java.util.Date?
A java.util.Date is a value object, and is a variation of the Memento or Token pattern.
It simply holds state - a long integer value of milliseconds since 1970-01-01 00:00:00.00 GMT. This is a very compact way to represent a date and time value, thus fits the idea of the Memento pattern very well.

You should use a java.util.Date as a value object to hold timestamps when you need to move such values between different parts of your software.

What then is the role of Calendar?
GregorianCalendar is many tens of times larger than the much simplier java.util.Date as it holds many additional information as part of its extensive internal state.

So don't use Calendar as a data transfer object.
Calendar is a variation of a strategy pattern, There are various implementations of calendar available including GregorianCalendar , JapaneseImperialCalendar. ChineseCalendar, HebrewCalendar are available from the IBM ICU4J Project.

Resources
Post a Comment

Labels

Java (159) Lucene-Solr (110) All (60) Interview (59) J2SE (53) Algorithm (37) Eclipse (35) Soft Skills (35) Code Example (31) Linux (26) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Continuous Integration (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Design (8) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Miscs (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Firefox (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Bit Operation (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts