Monday, July 22, 2013

PROGRAMS TO PERFORM PERATIONS USING DATE

Dear Friends
Today I am posting programs to perform date operations.

Program:
~~~~~~
Java program to find current date and to print the date after 10 days from current date.

import java.util.*;

public class aaa
{

public static void main(String[] args)
{
// get a calendar instance, which defaults to "now"
Calendar calendar = Calendar.getInstance();

// get a date to represent "today"
Date today = calendar.getTime();
System.out.println("today: " + today);

// add 10 day to the date/calendar
calendar.add(Calendar.DAY_OF_YEAR, 10);

// now get after 10 days
Date td = calendar.getTime();

// print out tomorrow's date
System.out.println("DATE AFTER 10 DAYS: " + td);
}

}

OUTPUT:
~~~~~~
today: Mon Jul 22 19:56:17 IST 2013
DATE AFTER 10 DAYS: Thu Aug 01 19:56:17 IST 2013

2.PROGRAM TO GET NEXT DAY,MONT YEAR DATE FROM CURRENT DATE:
public class aaa
{
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();

Date currentDate = calendar.getTime();
System.out.format("today: %s\n", currentDate);

// get the date/time one hour from now
calendar.setTime(currentDate);
calendar.add(Calendar.HOUR_OF_DAY, 1);
Date oneHour = calendar.getTime();
System.out.format("one hour: %s\n", oneHour);

// get tomorrow's date
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
System.out.format("tomorrow: %s\n", tomorrow);

// get next week's date
// note: may want to use WEEK_OF_MONTH or WEEK_OF_YEAR
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_YEAR, 7);
Date nextWeek = calendar.getTime();
System.out.format("next week: %s\n", nextWeek);

// get next month
calendar.setTime(currentDate);
calendar.add(Calendar.MONTH, 1);
Date nextMonth = calendar.getTime();
System.out.format("next month: %s\n", nextMonth);

// get next year
calendar.setTime(currentDate);
calendar.add(Calendar.YEAR, 1);
Date nextYear = calendar.getTime();
System.out.format("next year: %s\n", nextYear);
}
}

OUTPUT:
~~~~~~
today: Mon Jul 22 20:05:36 IST 2013
one hour: Mon Jul 22 21:05:36 IST 2013
tomorrow: Tue Jul 23 20:05:36 IST 2013
next week: Mon Jul 29 20:05:36 IST 2013
next month: Thu Aug 22 20:05:36 IST 2013
next year: Tue Jul 22 20:05:36 IST 2014

No comments:

Post a Comment

Animated Social Gadget - Blogger And Wordpress Tips