Joda Time - Java date and time API
Almost any application we develop, we need to manipulate dates. Always we need convinent methods to manipulate time,format time.
Recently I started using JODA API,a free, open-source Java library for working with dates and times. This API is a replacement for Date and Calendar classes.JODA APU has no dependencies outside core Java classes
The Key concepts in JODA are
Instant
Represents the number of milliseconds from 1970-01-01T00:00Z
Classes represent instant in JODA are Instant,DateTime,DateMidNight
Instant myInstant = new Instant(1000); /* This Means 1 second after 1970*/
myInstant = instant.plus(100);
myInstant = instant.minus(50);
DateTime can be created like
DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
DateTime endDate = new DateTime();
There are convinient methods provided in the API , like
daysBetween,getYear,getMonthOfYear
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(" Difference between " + endDate);
System.out.println(" and " + startDate + " is " + days + " days.");
Formatting the output is also quite esay in DateTime. The pattern neede can be passed to the toString() method of DateTime
System.out.println(dateTime.toString("y-M-d HH:mm:ss.SSS a")); // Output will be 2010-3-11 10:46:08.994 AM
System.out.println(dateTime.toString("yyyy-MM-dd"));// Output will be 2010-03-11
System.out.println(dateTime.toString("yyyy/MM/dd"));// Output will be 2010/03/11
System.out.println(dateTime.toString("dd/MM/yyyy"));// Output will be 11/03/2010
DateFormatter could also be used for formatted printing
DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
.appendDayOfWeekText()
// Week name
.appendLiteral(' ')
.appendMonthOfYearText()
// Month
.appendLiteral(' ')
.appendDayOfMonth(2)
//Day of month
.appendLiteral(' ').appendYear(4, 4).appendLiteral(' ')
.appendEraText().appendLiteral(' ').appendTimeZoneName()
.toFormatter();
System.out.println(monthAndYear.print(dateTime));
Partial
Some case we need is only the year/month/day, or the time of day, or even just the day of the week. Classes for dealing with time snippets are LocalDate and LocalTime
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(" Difference between " + endDate);
System.out.println(" and " + startDate + " is " + days + " days.");
Formatting the output is also quite esay in DateTime. The pattern neede can be passed to the toString() method of DateTime
System.out.println(dateTime.toString("y-M-d HH:mm:ss.SSS a")); // Output will be 2010-3-11 10:46:08.994 AM
System.out.println(dateTime.toString("yyyy-MM-dd"));// Output will be 2010-03-11
System.out.println(dateTime.toString("yyyy/MM/dd"));// Output will be 2010/03/11
System.out.println(dateTime.toString("dd/MM/yyyy"));// Output will be 11/03/2010
DateFormatter could also be used for formatted printing
DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
.appendDayOfWeekText()
// Week name
.appendLiteral(' ')
.appendMonthOfYearText()
// Month
.appendLiteral(' ')
.appendDayOfMonth(2)
//Day of month
.appendLiteral(' ').appendYear(4, 4).appendLiteral(' ')
.appendEraText().appendLiteral(' ').appendTimeZoneName()
.toFormatter();
System.out.println(monthAndYear.print(dateTime));
Partial
Some case we need is only the year/month/day, or the time of day, or even just the day of the week. Classes for dealing with time snippets are LocalDate and LocalTime
LocalDate localDate = SystemFactory.getClock().getLocalDate();
LocalTime localTime = SystemFactory.getClock().getLocalTime();
LocalDate localDate = new LocalDate(2010, 3, 10);// March 10, 2010
LocalTime localTime = new LocalTime(09, 30, 20, 0);
To have the Spans of time Joda provides three classes Duration,Period,Interval
The most interseting part of JODA is in Date calculations. For example if we need to add one week to the current time,
DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = current.plusWeeks(1);
To add 50 days
DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = now.plusDays(50);
Add 180 seconds from now:
DateTime current = SystemFactory.getClock().getDateTime();
DateTime later = now.plusSeconds(180);
Example using JODA Interval and Duration
private void intervalAndDuration() {
DateTime start = new DateTime(1977, 3, 22, 0, 0, 0, 0);
DateTime end = new DateTime(2010, 1, 27, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
start = interval.getStart();
Duration duration = interval.toDuration();
Period period = interval.toPeriod();
// or
Period weeks = interval.toPeriod(PeriodType.weeks());
Period years = interval.toPeriod(PeriodType.years());
Period days = interval.toPeriod(PeriodType.days());
System.out.println("YEARS " + years.getYears() + " WEEKS "
+ weeks.getWeeks()/54 + " DAYS " + days.getDays()/365);
}
Another simple AgeCalculator (Don't look for algorithm, method just to show useful methods in JODA API)
public void findAge(DateTime dateOfBirth, DateTime ageAsOn) {
if (ageAsOn.isBefore(dateOfBirth.getMillis())) {
System.out.println(" Wrong Dates !!! ");
System.exit(0);
}
int startMonth, endMonth, startYear, endYear;
int months, years;
int totalDays = 0;
startMonth = dateOfBirth.getMonthOfYear();
endMonth = ageAsOn.getMonthOfYear();
startYear = dateOfBirth.getYear();
endYear = ageAsOn.getYear();
//First calculate the year
if (endMonth >= startMonth)
years = endYear - startYear;
else
years = endYear - startYear - 1;
//Now calculate the months
if (endMonth >= startMonth)
months = endMonth - startMonth;
else {
if (ageAsOn.getDayOfMonth() > dateOfBirth.getDayOfMonth())
months = (12 - startMonth) + endMonth - 1;
else
months = (12 - startMonth) + endMonth - 2;
}
//Now calculate the days
if (endMonth != startMonth
&& ageAsOn.getDayOfMonth() != dateOfBirth.getDayOfMonth()) {
if (ageAsOn.getDayOfMonth() > dateOfBirth.getDayOfMonth()) {
totalDays = ageAsOn.getDayOfMonth()
- dateOfBirth.getDayOfMonth();
} else {
totalDays = (ageAsOn.getDayOfMonth() - 1)
- dateOfBirth.getDayOfMonth() + ageAsOn.getDayOfMonth();
}
}
String strAge = "Age as on " + ageAsOn.toString("dd-MM-yyyy") + " is "+ years + " years " + months + " month(s) " + totalDays+ " day(s)";
System.out.println(strAge);
}
Useful Links
http://joda-time.sourceforge.net/
http://www.ibm.com/developerworks/java/library/j-jodatime.html
System.out.println(strAge);
}
Useful Links
http://joda-time.sourceforge.net/
http://www.ibm.com/developerworks/java/library/j-jodatime.html
No comments:
Post a Comment