This blog shows an example on how Jython will make it easier for you to explore Java library or API.
In this sample I try to show how Jython could be used to learn a Java platform library or API interactively. Hopefully without going through the pain of code-compile-deploy-test cycles. After being familiar with certain library or API, we could come back the regular Java way to code.
In this blog I will pick a very common case. Nowadays, when we buy a house or car, a piece of land, or anything that is very expensive, seldom we will pay all full in cash. Usually we will apply for loan with banks or leasing companies. The bank or leasing company will then set up a installment that is scheduled regularly. They will choose a preset dates for the payments. Preset (or pre-agreed) dates could apply to payroll schedule, automated account posting, automated reminders, etc.
Java has a rich set of library or API almost for anything you need to. It’s the most comprehensive platform available in the market today. It runs in more devices than any other platforms (PC, servers, laptops, netbooks, handheld devices, smartphones, PDAs, game consoles, SIM cards, microcontrollers, etc.).
Back to topic, one way to do the preset installment is to use java.util.Calendar interface and one of its implementation: java.util.GregorianCalendar.
Because the class and interface that I mentioned above is part of Java Runtime libraries, it is automatically available for Jython as well (I am using Jython version 2.5.1, but it should be available on any versions of Jython).
from java.util import Calendar
from java.util import GregorianCalendar
def cal_to_str(c):
year = str(c.get(Calendar.YEAR))
month_int = c.get(Calendar.MONTH) + 1
if month_int < 10:
month = '0' + str(month_int)
else:
month = str(month_int)
day_int = c.get(Calendar.DAY_OF_MONTH)
if day_int < 10:
day = '0' + str(day_int)
else:
day = str(day_int)
return year + '-' + month + '-' + day
for i in range(12):
cal = GregorianCalendar(2009,8 - 1,29)
cal.add(Calendar.MONTH, i + 1)
print('Installment #%d: %s' % ((i + 1), cal_to_str(cal)))
The execution yielded:
Installment #1: 2009-09-29 Installment #2: 2009-10-29 Installment #3: 2009-11-29 Installment #4: 2009-12-29 Installment #5: 2010-01-29 Installment #6: 2010-02-28 Installment #7: 2010-03-29 Installment #8: 2010-04-29 Installment #9: 2010-05-29 Installment #10: 2010-06-29 Installment #11: 2010-07-29 Installment #12: 2010-08-29
Take a look on how the library handled well the date on the month of February, which has the maximum day of month of 28 (because 2010 is not a leap year).
Posted by dbaktiar 









.