Showing posts with label Date. Show all posts
Showing posts with label Date. Show all posts

Thursday, 19 May 2011

DateFormat and SimpleDateFormat Examples

Default date formats
The java.text.DateFormat class, and its concrete subclass java.text.SimpleDateFormat, provide a convenient way to convert strings with date and/or time info to and from java.util.Date objects. Figure 1 shows an example of using default DateFormat objects to format a date in a variety of ways:

// Make a new Date object. 
//It will be initialized to the current time.
Date now = new Date();
// See what toString() returns
System.out.println(" 1. " + now.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(now));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));
// Next, try the short, medium and long variants of the
// default time format
System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));
// For the default date-time format, the length of both the
// date and time elements can be specified.
Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance
(DateFormat.SHORT, DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance
(DateFormat.MEDIUM, DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance
(DateFormat.LONG, DateFormat.LONG).format(now));


Output:
 1. Tue Nov 04 20:14:11 EST 2003
2. 11/4/03 8:14 PM
3. 8:14:11 PM
4. Nov 4, 2003 8:14:11 PM
5. 8:14 PM
6. 8:14:11 PM
7. 8:14:11 PM EST
8. 11/4/03 8:14 PM
9. Nov 4, 2003 8:14 PM
10. November 4, 2003 8:14:11 PM EST

Friday, 15 April 2011

Get java.sql.Timestamp from date or current date

java.util.Date today = new java.util.Date();
System.out.println(new java.sql.Timestamp(today.getTime()));

Java program to get current date now

In this example program we have to get the current date at present now. We have used Calendar class for getting the current date and time instance. For printing date in the specific format we have used SimpleDateFormat class of "java.text" package.

Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=> " + dateNow);

Friday, 11 March 2011

Getting last day of month

public static int getLastDayOfMonth {
//
// Get a calendar instance
//
Calendar calendar = Calendar.getInstance();

//
// Get the last date of the current month.
// To get the last date for a
// specific month you can set the calendar month
//using calendar object
// calendar.set(Calendar.MONTH, theMonth) method.
//
int lastDate = calendar.getActualMaximum(Calendar.DATE);

//
// Set the calendar date to the last date of the month so then we can
// get the last day of the month
//
calendar.set(Calendar.DATE, lastDate);
int lastDay = calendar.get(Calendar.DAY_OF_WEEK);

//
// Print the current date and the last date of the month
//
System.out.println("Last Date: " + calendar.getTime());

//
// The lastDay will be in a value from 1 to 7 where 1 = monday and 7 =
// saturday respectively.
//
return lastDay;
}

Calculating difference between 2 dates

Again to do Date arithematic we need Calender class.

Following function takes 2 dates and prints difference in days, millis etc...you can make you own function to return long etc...

public static void printDiff(Date dat1, Date dat2)
{
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

// Set the date for both of the calendar instance
cal1.setTime(dat1);
cal2.setTime(dat2);

// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();

// Calculate difference in milliseconds
long diff = milis2 - milis1;

// Calculate difference in seconds
long diffSeconds = diff / 1000;

// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);

// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);

// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}

Date arithematic


The java.util.Calendar allows us to do a date arithmetic function such as add or subtract a unit of time to the specified date field.
The method that done this process is the Calendar.add(int field, int amount). Where the value of the field can be Calendar.DATE, Calendar.MONTH, Calendar.YEAR. So this mean if you want to subtract in days, months or years use Calendar.DATE, Calendar.MONTH or Calendar.YEAR respectively.

import java.util.Calendar;

public class CalendarAddExample {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();

System.out.println("Today : " + cal.getTime());

// Subtract 30 days from the calendar
cal.add(Calendar.DATE, -30);
System.out.println("30 days ago: " + cal.getTime());

// Add 10 months to the calendar
cal.add(Calendar.MONTH, 10);
System.out.println("10 months later: " + cal.getTime());

// Subtract 1 year from the calendar
cal.add(Calendar.YEAR, -1)
System.out.println("1 year ago: " + cal.getTime());
}
}

Java Date API


java.util.
Class Date
java.lang.Object
extended by java.util.Date
All Implemented Interfaces:
Cloneable, Comparable, Serializable
Direct Known Subclasses:
Date, Time, Timestamp
public class Date extends Object
implements Serializable, Cloneable, Comparable
The class Date represents a specific instant with millisecond precision.

See here for more resources.

Some examples of using it:

Converting Date to stringConverting string to DateDate arithematic
Calculating difference between 2 dates
Getting last day of month


Converting Date to string

Consider we create date of today:

        // Get the date today using Calendar object.
        Date today = Calendar.getInstance().getTime();    
        String dateString = date2String(today);

package org.kodejava.example.java.util;

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

public static String date2String(Date today){
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);
}

Sunday, 28 November 2010

How do I convert String to Date object?

The following code shows how we can convert a string representation of date into java.util.Date object.
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.


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

public Date StringToDate
{
         DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

       try
        {
            Date today = df.parse("20/12/2005");           
           System.out.println("Today = " + df.format(today));
      } catch (ParseException e)
      {
            System.out.println("Cannot convert to date "+e);
        }
    
}
And here is the result of our code:
Today = 20/12/2005
The example starts by creating an instance of SimpleDateFormat with "dd/MM/yyyy" format which mean that the date string is formatted in day-month-year sequence.
Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.
Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.
Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800