Skip to main content

Working with Date and Time

 
import java.util.*;
import java.text.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *This class has all method to be used by Timesheet throught the date and time related operations
 * @author Hemraj
 */
public class DateTime {

    /**
     * Change the date represented by Date object into the date format that is accepted by MS SQL Server 
     * @param d
     * @return
     */
    public String dateTime(Date d) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(d);
        int yy = c.get(Calendar.YEAR);
        int mm = c.get(Calendar.MONTH) + 1;
        int dd = c.get(Calendar.DATE);
        int m = c.get(Calendar.MINUTE);
        int s = c.get(Calendar.SECOND);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        String timeStamp = yy + "-" + mm + "-" + dd + " " + hour + ":" + m + ":" + s;
        return timeStamp;
    }

    /**
     * Covert the indian like 12/3/3009 date format into database date fromat lilke yyyy-mm-dd 
     * @param d
     * @return
     */
    public String dateFormat(String d) {
        int i1 = d.indexOf("/");
        int i2 = d.indexOf("/", i1 + 1);
        String dd = d.substring(0, i1).trim();
        String mm = d.substring(i1 + 1, i2).trim();
        String yy = d.substring(i2 + 1).trim();
        return yy + "-" + mm + "-" + dd;
    }

    /**
     * change date like 2008-01-14 15:53:06.000 into 14/1/2008
     * @param d
     * @return
     */
    public String formatDate(String d) {
        //d=d.substring(0,d.indexOf(" "));
        int i = d.indexOf("-");
        String yyyy = d.substring(0, i);
        int j = d.indexOf("-", i + 1);
        String mm = d.substring(+ 1, j);
        String dd = d.substring(+ 1, j + 1 + 2);
        return dd + "/" + mm + "/" + yyyy;
    }

    /**
     * Change the database date format into dd/mm/yyyy format
     * @param d
     * @return
     */
    public static String dbToIn(String d) {
        d = d.substring(0, d.indexOf(" "));
        int i = d.indexOf("-");
        String yyyy = d.substring(0, i);
        int j = d.indexOf("-", i + 1);
        String mm = d.substring(+ 1, j);
        String dd = d.substring(+ 1);
        return dd + "/" + mm + "/" + yyyy;
    }

    /**
     * Change the date format of Date object into indian format(dd/mm/yyyy); 
     * @param date
     * @return
     */
    public String formatDate(java.util.Date date) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(date);
        int yy = c.get(Calendar.YEAR);
        int mm = c.get(Calendar.MONTH) + 1;
        int dd = c.get(Calendar.DATE);
        String timeStamp = dd + "/" + mm + "/" + yy;
        return timeStamp;

    }

    public String getDayName(int i) {
        String days[] = {"Mo""Tu""We""Th""Fr""Sa""Su"};
        return days[- 1];
    }

    /**
     * Method to convert string like dd/mm/yyyy into Date object. 
     * E.g 12/02/2004 will be passed as argument at method gives you Date object
     * that contain the above date.
     * @param d
     * @return Date returns the Date object
     */
    public java.util.Date dateObject(String d) throws ParseException {
        int i1 = d.indexOf("/");
        int i2 = d.indexOf("/", i1 + 1);
        String dd = d.substring(0, i1).trim();
        String mm = d.substring(i1 + 1, i2).trim();
        String yy = d.substring(i2 + 1).trim();
        //return yy+"-"+mm+"-"+dd;
        Calendar c = new java.util.GregorianCalendar(Integer.parseInt(yy)Integer.parseInt(mm) - 1Integer.parseInt(dd));
        return c.getTime();
    }

    /**
     * @author Hemraj
     * Calculate the difference between two dates represented by 2 java.util.Date object
     * @param first First Date object to be subtracted
     * @param second second date object from which fisrt date object to be subtracted
     * @return long value. Number of days
     */
    public long dateDiffInDays(java.util.Date first, java.util.Date second) {
        Calendar cFirst = new java.util.GregorianCalendar();
        cFirst.setTime(first);
        Calendar cSecond = new java.util.GregorianCalendar();
        cSecond.setTime(second);

        long milliseconds1 = cFirst.getTimeInMillis();
        long milliseconds2 = cSecond.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        //long diffSeconds = diff / 1000;
        //long diffMinutes = diff / (60 * 1000);
        //long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        return diffDays;

    }

    /**
     * 
     * @param first
     * @param second
     * @return
     */
    public int campareDates(java.util.Date first, java.util.Date second) {
//        Calendar cFirst = new java.util.GregorianCalendar();
//        cFirst.setTime(first);
        return first.compareTo(second);

    }

    /**
     * Method to convert string like dd/mm/yyyy into Date object. 
     * E.g 12/02/2004 will be passed as argument at method gives you Date object
     * that contain the above date.
     * @param  d java.sql.Date object from resultset
     * @return Date returns the Date object
     */
    public java.util.Date dateObject(java.sql.Date d) {
        return (java.util.Date) d;
    }

    /**
     * get the next date from specified date for specified number of days
     * @param cd
     * @param days
     * @return
     */
    public java.util.Date nextDate(java.util.Date cd, int days) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(cd);
        c.add(Calendar.DAY_OF_MONTH, days);
        return c.getTime();
    }

    /**
     * get previous date from specified date for specified number of days.
     * @param cd
     * @param days
     * @return
     */
    public java.util.Date previousDate(java.util.Date cd, int days) {
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(cd);
        c.add(Calendar.DAY_OF_MONTH, -days);
        return c.getTime();
    }

    /**
     * get the name of day of date like dd/mm/yyyy
     * @param d
     * @return
     */
    public String getDayName(String d) throws Exception {
        java.util.Date date = dateObject(d);
        Calendar c = new java.util.GregorianCalendar();
        c.setTime(date);
        return getDayName(date);
    }

    /**
     * Get name of the day represented by specified date object
     * @param d
     * @return
     */
    public String getDayName(Date d) {
        DateFormat f = new SimpleDateFormat("EEEE");
        try {
            return f.format(d);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    public String getDaysName(int day,int month)
    {
         Calendar c1 = Calendar.getInstance();
         Calendar c2 = Calendar.getInstance()// new GregorianCalendar();
         c2.setTime(new Date());
         int year = c2.get(Calendar.YEAR);
         c1.set(year, month, day);
         String name=getDayName(c1.getTime());
         return name.substring(0,2);
    }
    public static int daysInMonth(int month) {

        System.out.println("4. No of Days in a month for a given date\n");
        Calendar c1 = Calendar.getInstance()// new GregorianCalendar();
        //c1.setTime(cd);
        Calendar c2 = Calendar.getInstance()// new GregorianCalendar();
        c2.setTime(new Date());
        int year = c2.get(Calendar.YEAR);
        //int month = c1.get(Calendar.MONTH);
        c1.set(year, month, 1);
        // int days = c1.get(Calendar.DATE);
        int[] daysInMonths = {312831303130313130313031};
        daysInMonths[1] += isLeapYear(year) ? 1 : 0;
        System.out.println("Days in " + month + "th month for year" + year + "is " + daysInMonths[c1.get(Calendar.MONTH)]);
        System.out.println();
        System.out.println("-------------------------------------");
        return daysInMonths[c1.get(Calendar.MONTH)];
    }

    public static boolean isLeapYear(int year) {

        if ((year % 100 != 0) || (year % 400 == 0)) {
            return true;
        }
        return false;
    }

    public static void main(String ar[]) throws Exception {
        //System.out.println(new DateTime().getDayName("13/4/2008"));
        //System.out.println(new DateTime().getDayName(new Date()));
        //System.out.println("Days = "+daysInMonth(7));
        int days=daysInMonth(3);
        for(int i=1;i<=days;i++)
        {
            System.out.println(i+"="+new DateTime().getDaysName(i, 3));
        }
    }
}


Comments

Popular posts from this blog

Using HyperSQL (HSQLDB)

HSQLDB is a portable RDBMS implemented in pure java. It can be embedded with your application as well as can be used separately. It is very a small database that supports almost all features of the standard database system. It comes with small jar file that can be found in lib folder. The HSQLDB jar package is located in the /lib directory of the ZIP package and contains several components and programs. Core components of jar file are : HyperSQL RDBMS Engine (HSQLDB), HyperSQL JDBC Driver, Database Manager, and Sql Tool. Installing and Using Download: download latest release of HyperSQL database from http://hsqldb.org website and extract it. You will see following contents. Here "bin" directory contains some batch files those can be used to run a swing based GUI tool. You can use runManagerSwing.bat to connect to database, but database must be on before running it. Directory lib contains File hsqldb.jar . It is the database to be used by you. Running database First

How to handle values from dynamically generated elements in web page using struts2

Some time you will see the form containing the button " Add More " . This facility is provided for the user to get the values for unknown number of repeating for some information. for example when you are asking to get the projects details from user, you need to put the option to add the more project for the user since you don't known how many projects user have. In the HTML form, you repeat the particular section to get the multiple values for those elements. In Html page , you can put the option to add new row of elements or text fields by writing the java script or using JQuery API. Now, the question is that how to capture the values of dynamically generated text fields on the server. Using the servlet programming you can get the values by using getParameters() method that resultants the array of the parameter having the same name. But this limit you to naming the text fields in the HTML form. To ally this approach, you have to take the same name for t

In Process Mode of HSQLDB in web application.

If you want to use the database into your web application, you can use the HSQLDB in In_Process mode. In this mode, you can embed the HSQLDB into your web application and it runs as a part of your web application programm in the same JVM. In this mode, the database does not open any port to connect to the application on the hosing machine and you don't need to configure anything to access it. Database is not expposed to other application and can not be accessed from any dabase tools like dbVisualizer etc. In this mode ,database will be unknown from any other person except you. But in the 1.8.0 version, you can use Server intance for external as well as in process access.  To close the databse, you can issue SHUTDOWN command as an SQL query.   In the in-process mode, database starts from JDBC with the associated databse file provided through  connection URL. for example   DriverManager.getConnection("jdbc:hsqldb:mydatabase","SA","");   Here myd