Wednesday, December 14, 2011

Joda-Time

@Grab('joda-time:joda-time:2.0')
import org.joda.time.*
//see also http://groovycookbook.org/basic_types/dates_times_joda/

public boolean isAfterPayDay(DateTime datetime) {
  if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
    return datetime.getDayOfMonth() > 26;
  }
  return datetime.getDayOfMonth() > 28;
}

public Days daysToNewYear(LocalDate fromDate) {
  LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
  return Days.daysBetween(fromDate, newYear);
}

public boolean isRentalOverdue(DateTime datetimeRented) {
  Period rentalPeriod = new Period().withDays(2).withHours(12);
  return datetimeRented.plus(rentalPeriod).isBeforeNow();
}

public String getBirthMonthText(LocalDate dateOfBirth) {
  return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}

DateTime dt = new DateTime();
int month = dt.getMonthOfYear();

DateTime year2000 = dt.withYear(2000);
DateTime twoHoursLater = dt.plusHours(2);

String monthName = dt.monthOfYear().getAsText();
String frenchShortName = dt.monthOfYear().getAsShortText(Locale.FRENCH);
boolean isLeapYear = dt.year().isLeap();
DateTime rounded = dt.dayOfMonth().roundFloorCopy();

println (new DateTime().withDayOfMonth(4).withMonthOfYear(7).withYear(1899).toString('EEE, dd/MM/yyyy HH:mm:ss'))

println (new Date().parse("d/M/yyyy H:m:s","21/3/2008 17:30:20"))
println (Calendar.instance.time.format('MMM dd, yyyy'))
// standard groovy flavor, see also http://groovycookbook.org/basic_types/dates_times/

No comments:

Post a Comment