Showing posts with label Date and Time in Java. Show all posts
Showing posts with label Date and Time in Java. Show all posts

Wednesday, June 4, 2014

Java Examples

Example using ArrayList:

import java.util.ArrayList;
import java.util.Iterator;
/**
 *
 * @author rdayala
 */
public class WelcomeJava {
    public static void main(String args[])
    {
        System.out.println("Welcome to Java Learning!");       
        Integer x = 5;
        Object obj = 5;
        int y = x.intValue();
        int z = ((Integer)obj).intValue();
        String name = "Raghu";
       
        System.out.printf("Y : %d, Z : %d\n\n", y, z);
       
        ArrayList list = new ArrayList();
        list.add("Raghu");
        list.add(1);
        list.add(12.5);              
                     
        Class listClass = list.getClass();
        System.out.println("list type: " + listClass.getName());
        System.out.println("list size: " + list.size());
        System.out.println("list elements are:");
       
// traversing ArrayList using iterator

        Iterator it = list.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
               
    }
}

Another Example:

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.nio.file.*;
public class HelloWorld {

    /**
     * @param args the command line arguments
     */
    public static void main(String []args) {
        // TODO code application logic here
        System.out.println("Hello,World - Raghu!");
        System.out.println("Welcome to Java Programming Language");
       
        String valueFromUI = JOptionPane.showInputDialog("Enter Your Name:");
        System.out.println("Your name is: " + valueFromUI + ", Lenght of Name:" + valueFromUI.length());
       
        System.out.println("Enter a value from console:");
        Scanner input = new Scanner(System.in);       
        int value = input.nextInt();
       
        System.out.println("Value read from console is : " + value);
       
        int []num = new int[5];
        Class cls = num.getClass();
       
        System.out.println("Type of the array : " + cls.getName());
       
        int[] numArray = {1, 2, 3, 4, 5};
        int[] cpArray;
        cpArray = new int[5];
        System.arraycopy(numArray, 0, cpArray, 0, numArray.length);
        cpArray[3]=7;
       
        System.out.println("Num Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nCopy Array is: ");
        for(int val : cpArray)
            System.out.print(val + " ");
       
        int[] clArray;
        clArray = numArray.clone();
        clArray[3]=8;
       
        System.out.println("\nNum Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nClone Array is: ");
        for(int val : clArray)
            System.out.print(val + " ");
       
        FileSystem fs = FileSystems.getDefault();
        System.out.println("\nFileSystem is : " + fs.toString());
       
        Iterable<Path> roots = FileSystems.getDefault().getRootDirectories();
        for(Path rt : roots)
            System.out.println("\nRoot is: " + rt.toString());
               
        Path path = FileSystems.getDefault().getPath("home", "user", "images.gif");
        System.out.println("\nPath is : " + path.toString());

    }
}

Exception Example:

public class ExceptionTest {
       
    public static void main(String[] args) {
        int a = 15, b = 0;
        int c;
        try {
                if( a == 15)
                    throw new Exception("Please enter valid number for a");
                c = a / b;
        } catch(ArithmeticException e) {
            System.out.println("Inside catch block");
        }
        catch(Exception e)
        {
            System.out.println("General exception caught by throw statement.");
        }
        finally {
            System.out.println("Inside finally block");           
        }
    }
   
}

Convert a string to date in Java:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) throws Exception {
    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date dateToday = dateFormat.parse("25/06/2011");
    System.out.println(myDateFormat.format(dateToday));
  }
}

Date & Time Example:

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatesAndTimes {
    public static void main(String[] args)
    {
        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());
        System.out.println("Timezone is : " + cal.getTimeZone().getID());
       
        Date todaysDate = new Date();
        int compareTo = today.compareTo(todaysDate);
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm:ss a ZZZZ");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);
       
        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
       
        DateFormat df1 = DateFormat.getTimeInstance();
        String formatString1 = df1.format(todaysDate);
        System.out.println(formatString1);
       
        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df2 = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df2.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);
       
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);
       
        Date date1 = new Date();
        Date date2 = new Date();
        long time1 = date1.getTime();
        long time2 = date2.getTime();
       
        long diff = time2 - time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));      
       
        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }
       
        System.out.println("Today is : " + cal.toString());
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));
       
        //long start = System.currentTimeMillis();
        // do some other stuff…
        // long end = System.currentTimeMillis();
        // long elapsedTime = end – start;
       
    }
}

Serialization Example:

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ObjectSerializeTest implements Serializable {
   
    private int age;
    private String name;
   
    public void setAge(int ageVal) {
        age = ageVal;
    }
   
    public void setName(String nameVal) {
        name = nameVal;
    }
   
    public void Display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
   
    public static void main(String[] args) {
        ObjectSerializeTest obj1 = new ObjectSerializeTest();
        obj1.setAge(32);
        obj1.setName("Raghunath");       
       
        FileOutputStream fops;
        try {
            fops = new FileOutputStream("raghu.txt");      
            ObjectOutputStream oos = new ObjectOutputStream(fops);
            oos.writeObject(obj1);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        FileInputStream fips;
        try {
            fips = new FileInputStream("raghu.txt");
            ObjectInputStream oips = new ObjectInputStream(fips);
            ObjectSerializeTest obj2 = (ObjectSerializeTest)oips.readObject();
            obj2.Display();
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }   
}


Singleton using Enum:

enum MySingleton
{
    RAGHU;
    public void sayHello()
    {
        System.out.println("Hello Raghu!");
    }
   
    public void sayBye()
    {
        System.out.println("Bye Raghu!");
    }
}
public class Singleton {
    public static void main(String[] args)
    {
        MySingleton ms = MySingleton.RAGHU;
        ms.sayHello();
        ms.sayBye();
        MySingleton ms1 = MySingleton.RAGHU;
       
        if(ms == ms1)
            System.out.println("Referring to same singleton class");
    }
}

Final fields having different values, initialized using Constructor:

public class FinalFieldsExample {
    public final int a;
   
    FinalFieldsExample(int val) {
        a = val;
    }
   
    public void display()
    {
        System.out.println("The value of final field a is : " + a);
    }
   
    public static void main(String[] args) {
        FinalFieldsExample t1 = new FinalFieldsExample(10);
        t1.display();
       
        FinalFieldsExample t2 = new FinalFieldsExample(20);
        t2.display();       
       
    }
   
}


Thursday, March 6, 2014

Dates and Times in Java

Java has good built-in support for working with dates and times.

3 primary classes:

java.util.Date - kind of deprecated. Use java.util.Calendar class
java.sql.Date
java.util.Calendar

Many of the methods in the java.util.Date class have become deprecated.

Finding Today's Date:

        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());

O/p:
Today is : Thu Mar 06 11:36:50 IST 2014
Today is : Thu Mar 06 11:36:50 IST 2014

Converting between Date and Calendar objects

// Date to Calendar conversion
Date myDate = new java.util.Date();
Calendar myCal = Calendar.getInstance();
myCal.setTime(myDate);

// Calendar to Date conversion
Calendar newCal = Calendar.getInstance();
Date newDate = newCal.getTime();

In most Java applications, you'll find uses of both the Date and Calendar classes; thus knowing how to convert from one to the other is something you want to be familiar with.

Best practice is, you create utility methods to perform these conversations so that you can convert from any place in your code with a simple method call.

public static Date calToDate(Calendar cal) {
          return cal.getTime();
}

public static Calendar dateToCal(Date date) {
          Calendar myCal = Calendar.getInstance();
          myCal.setTime(date);
          return myCal;
}


Printing Date/Time in a Given Format:

Java contains formattign classes that can be used to format a date into a desired format.

Example:
        import java.text.SimpleDateFormat;

        Date todaysDate = new Date();
        SimpleDateFormat formatter =

                                      new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);

o/p:
Thu, 06 Mar 2014 11:57:07

 

Using this format: "EEEE, d-MMM-yyyy HH:mm:ss a", 
o/p :
Thursday, 6-Mar-2014 11:55:07 AM

Using this format: "EEEE, dd-MMMM-yyyy HH:mm:ss a",
o/p:
Thursday, 06-March-2014 11:58:13 AM

Using Pre-defined format strings:

import java.text.DateFormat;

        DateFormat df = DateFormat.getDateInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014


        DateFormat df = DateFormat.getTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
12:02:33 PM


        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014 12:02:56 PM

More useful things:

Calendar cal = Calendar.getInstance();

cal.getTimeZone().getDisplayName() - India Standard Time
cal.getTimeZone().toString() - sun.util.calendar.ZoneInfo
                     [id= "Asia/Calcutta", offset=19800000, dstSavings=0, useDaylight=false, transitions=6, lastRule=null]
cal.getTimeZone().getID() - Asia/Calcutta

Parsing Strings into Dates

        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }

o/p:
Parsed Date: Sat Jan 12 15:30:32 IST 1952

The DateFormat object is used to parse a String and obtain a java.util.Date object.
 The java.sql.Date, java.sql.Time, and java.sql.Timestamp classes contain a static method called valueOf() which can also be used to parse simple date strings of the format "yyyy-mm-dd". This is very useful for converting dates you might use in SQL strings while using JDBC, into Date objects.     String date = "2000-11-01";
    java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);

Adding to or Substracting from a Date or Calendar:

If you are using Date object, the technique for adding or substracting dates is to first convert the object to a long value using the getTime() method of Date object.

The getTime() method returns the time as measured in milliseconds since the epoch. You then perofrm arithmetic on the long values and finally convert back to date objects.

        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);

You perform date arithmetic directly on Calendar objects using the add() method.
    
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);

Difference between Two Dates

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long diff = time2 – time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));

Usecase: Calculating expiry days for an item:

        public static void daysTillExpired(Date expDate) {
            Date currentDate = new Date();
            long expTime = expDate.getTime();
            long currTime = currentDate.getTime();
            long diff = expTime – currTime;
            return diff/(1000*60*60*24);
        }

Comparing Dates

        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }

The dates must be the same down to the millisecond level in order for the equals() method to return true.

The Date class also has an after() method, which is used similar to before() method to determine if the date on which it is called occurs after the date passed in as parameter.

Another useful method for comparing two dates is the compareTo() method of the Date class. It returns an integer value. 0 - indicates dates are equal.

Finding the day of week/month/year or week number:

        Calendar cal = Calendar.getInstance();
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));

Calculating elapsed time:

By calculating elapsed time, we can determine how long it takes to do something or how long a process takes to complete.

        long start = System.currentTimeMillis();
        // do some other stuff…
        long end = System.currentTimeMillis();
        long elapsedTime = end – start;

System.currentTimeMillis() method is the time since January 1, 00:00:00, 1970 in milliseconds.

JDK 1.5 adds a nanoTime() method to the System class, which gives even more precise timing, down to nano seconds.