中国阴历算法part1
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;public class Lunar {
private int year;
private int month;
private int day;
private boolean leap;
final static String chineseNumber[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
static SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
final static long[] lunarInfo = new long[]
{0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0}; //====== 传回农历 y年的总天数
final private static int yearDays(int y) {
int i, sum = 348;
for (i = 0x8000; i > 0x8; i >>= 1) {
if ((lunarInfo[y - 1900] & i) != 0) sum += 1;
}
return (sum + leapDays(y));
} //====== 传回农历 y年闰月的天数
final private static int leapDays(int y) {
if (leapMonth(y) != 0) {
if ((lunarInfo[y - 1900] & 0x10000) != 0)
return 30;
else
return 29;
} else
return 0;
} //====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0
final private static int leapMonth(int y) {
return (int) (lunarInfo[y - 1900] & 0xf);
} //====== 传回农历 y年m月的总天数
final private static int monthDays(int y, int m) {
if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)
return 29;
else
return 30;
} //====== 传回农历 y年的生肖
final public String animalsYear() {
final String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
return Animals[(year - 4) % 12];
} //====== 传入 月日的offset 传回干支, 0=甲子
final private static String cyclicalm(int num) {
final String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
final String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
return (Gan[num % 10] + Zhi[num % 12]);
} //====== 传入 offset 传回干支, 0=甲子
final public String cyclical() {
int num = year - 1900 + 36;
return (cyclicalm(num));
} /**
* 传出y年m月d日对应的农历.
* yearCyl3:农历年与1864的相差数 ?
* monCyl4:从1900年1月31日以来,闰月数
* dayCyl5:与1900年1月31日相差的天数,再加40 ?
* @param cal
* @return
*/
public Lunar(Calendar cal) {
int yearCyl, monCyl, dayCyl;
int leapMonth = 0;
Date baseDate = null;
try {
baseDate = chineseDateFormat.parse("1900年1月31日");
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
} //求出和1900年1月31日相差的天数
int offset = (int) ((cal.getTime().getTime() - baseDate.getTime()) / 86400000L);
dayCyl = offset + 40;
monCyl = 14; //用offset减去每农历年的天数
// 计算当天是农历第几天
//i最终结果是农历的年份
//offset是当年的第几天
int iYear, daysOfYear = 0;
for (iYear = 1900; iYear < 2050 && offset > 0; iYear++) {
daysOfYear = yearDays(iYear);
offset -= daysOfYear;
monCyl += 12;
}
if (offset < 0) {
offset += daysOfYear;
iYear--;
monCyl -= 12;
}
//农历年份
year = iYear; yearCyl = iYear - 1864;
leapMonth = leapMonth(iYear); //闰哪个月,1-12
leap = false; //用当年的天数offset,逐个减去每月(农历)的天数,求出当天是本月的第几天
int iMonth, daysOfMonth = 0;
for (iMonth = 1; iMonth < 13 && offset > 0; iMonth++) {
//闰月
if (leapMonth > 0 && iMonth == (leapMonth + 1) && !leap) {
--iMonth;
leap = true;
daysOfMonth = leapDays(year);
} else
daysOfMonth = monthDays(year, iMonth); offset -= daysOfMonth;
//解除闰月
if (leap && iMonth == (leapMonth + 1)) leap = false;
if (!leap) monCyl++;
}
//offset为0时,并且刚才计算的月份是闰月,要校正
if (offset == 0 && leapMonth > 0 && iMonth == leapMonth + 1) {
if (leap) {
leap = false;
} else {
leap = true;
--iMonth;
--monCyl;
}
}
//offset小于0时,也要校正
if (offset < 0) {
offset += daysOfMonth;
--iMonth;
--monCyl;
}
month = iMonth;
day = offset + 1;
}
public static String getChinaDayString(int day) {
String chineseTen[] = {"初", "十", "廿", "卅"};
int n = day % 10 == 0 ? 9 : day % 10 - 1;
if (day > 30)
return "";
if (day == 10)
return "初十";
else
return chineseTen[day / 10] + chineseNumber[n];
}
public String toString() {
return year + "年" + (leap ? "闰" : "") + chineseNumber[month - 1] + "月" + getChinaDayString(day);
}
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;public class Lunar {
private int year;
private int month;
private int day;
private boolean leap;
final static String chineseNumber[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
static SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
final static long[] lunarInfo = new long[]
{0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0}; //====== 传回农历 y年的总天数
final private static int yearDays(int y) {
int i, sum = 348;
for (i = 0x8000; i > 0x8; i >>= 1) {
if ((lunarInfo[y - 1900] & i) != 0) sum += 1;
}
return (sum + leapDays(y));
} //====== 传回农历 y年闰月的天数
final private static int leapDays(int y) {
if (leapMonth(y) != 0) {
if ((lunarInfo[y - 1900] & 0x10000) != 0)
return 30;
else
return 29;
} else
return 0;
} //====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0
final private static int leapMonth(int y) {
return (int) (lunarInfo[y - 1900] & 0xf);
} //====== 传回农历 y年m月的总天数
final private static int monthDays(int y, int m) {
if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)
return 29;
else
return 30;
} //====== 传回农历 y年的生肖
final public String animalsYear() {
final String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
return Animals[(year - 4) % 12];
} //====== 传入 月日的offset 传回干支, 0=甲子
final private static String cyclicalm(int num) {
final String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
final String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
return (Gan[num % 10] + Zhi[num % 12]);
} //====== 传入 offset 传回干支, 0=甲子
final public String cyclical() {
int num = year - 1900 + 36;
return (cyclicalm(num));
} /**
* 传出y年m月d日对应的农历.
* yearCyl3:农历年与1864的相差数 ?
* monCyl4:从1900年1月31日以来,闰月数
* dayCyl5:与1900年1月31日相差的天数,再加40 ?
* @param cal
* @return
*/
public Lunar(Calendar cal) {
int yearCyl, monCyl, dayCyl;
int leapMonth = 0;
Date baseDate = null;
try {
baseDate = chineseDateFormat.parse("1900年1月31日");
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
} //求出和1900年1月31日相差的天数
int offset = (int) ((cal.getTime().getTime() - baseDate.getTime()) / 86400000L);
dayCyl = offset + 40;
monCyl = 14; //用offset减去每农历年的天数
// 计算当天是农历第几天
//i最终结果是农历的年份
//offset是当年的第几天
int iYear, daysOfYear = 0;
for (iYear = 1900; iYear < 2050 && offset > 0; iYear++) {
daysOfYear = yearDays(iYear);
offset -= daysOfYear;
monCyl += 12;
}
if (offset < 0) {
offset += daysOfYear;
iYear--;
monCyl -= 12;
}
//农历年份
year = iYear; yearCyl = iYear - 1864;
leapMonth = leapMonth(iYear); //闰哪个月,1-12
leap = false; //用当年的天数offset,逐个减去每月(农历)的天数,求出当天是本月的第几天
int iMonth, daysOfMonth = 0;
for (iMonth = 1; iMonth < 13 && offset > 0; iMonth++) {
//闰月
if (leapMonth > 0 && iMonth == (leapMonth + 1) && !leap) {
--iMonth;
leap = true;
daysOfMonth = leapDays(year);
} else
daysOfMonth = monthDays(year, iMonth); offset -= daysOfMonth;
//解除闰月
if (leap && iMonth == (leapMonth + 1)) leap = false;
if (!leap) monCyl++;
}
//offset为0时,并且刚才计算的月份是闰月,要校正
if (offset == 0 && leapMonth > 0 && iMonth == leapMonth + 1) {
if (leap) {
leap = false;
} else {
leap = true;
--iMonth;
--monCyl;
}
}
//offset小于0时,也要校正
if (offset < 0) {
offset += daysOfMonth;
--iMonth;
--monCyl;
}
month = iMonth;
day = offset + 1;
}
public static String getChinaDayString(int day) {
String chineseTen[] = {"初", "十", "廿", "卅"};
int n = day % 10 == 0 ? 9 : day % 10 - 1;
if (day > 30)
return "";
if (day == 10)
return "初十";
else
return chineseTen[day / 10] + chineseNumber[n];
}
public String toString() {
return year + "年" + (leap ? "闰" : "") + chineseNumber[month - 1] + "月" + getChinaDayString(day);
}
public static void main(String[] args) throws ParseException {
Calendar today = Calendar.getInstance();
today.setTime(chineseDateFormat.parse("2004年1月22日"));
Lunar lunar = new Lunar(today); System.out.println("北京时间:" + chineseDateFormat.format(today.getTime()) + " 农历" + lunar);
}
}
<html>
<head>
<title>jsp万年历</title>
<style type="text/css">
<!--
input { font-size:9pt;}
A:link {text-decoration: underline; font-size:9pt;color:000059}
A:visited {text-decoration: underline; font-size:9pt;color:000059}
A:active {text-decoration: none; font-size:9pt}
A:hover {text-decoration:underline;color:red}
body,table {font-size: 9pt}
tr,td{font-size:9pt}
-->
</style>
</head>
<body alink="#FF0000" link="#000099" vlink="#CC6600" topmargin="8" leftmargin="0" bgcolor="#F0F6E2">
<table width=640 bgcolor="#F0F6E2"><tr><td >
<%
//打印年月抬头
out.println("<div align=\"center\"><b><font size=\"2\">"+year+"年"+(month+1)+"月</font></b> ");
if(ty==0)
{
out.println(" <b><font size=\"2\">"+mten[everymonth[j][14]]+mtwelve[everymonth[j][15]]+"年</font></b> ");
}
else
{
out.println(" <b><font size=\"2\">"+mten[everymonth[j][14]]+mtwelve[everymonth[j][15]]+"/"+mten[everymonth[j+1][14]]+mtwelve[everymonth[j+1][15]]+"年</font></b></div>");
}
%>
<%
out.println("<form method=\"POST\" action=\"year.jsp\">");
//打印上一月,下一月
int ly,ny;
ly=year;
ny=year;
int last=month;
if (last==0){
last=12;
ly--;
}
int next=month+1;
if (next==12){
next=0;
ny++;
}
if (ly>1900)
out.println(" <div align='center'> <a href=\"year.jsp?year="+ly+"&month="+last+"\"><<上一个月</a> ");
if (ny<=2020)
out.println("<a href=\"year.jsp?year="+ny+"&month="+(next+1)+"\">下一个月>></a> ");
%>
<font color="#000000">年份:
<select name="year" onChange="">
<%
int ii;
for(ii=2020;ii>=1901;ii--){
%>
<option value="<%=ii%>" <%if(ii==year) out.println("selected");%>>
<%out.println(ii);%>
</option>
<%
}
%>
</select>
</font><font color="#000000">年</font><font color="#000000">
月份:
<select name="month" onChange="">
<%
for(ii=1;ii<=12;ii++){
%>
<option value="<%=ii%>" <%if(ii==month+1) out.println("selected");%>><%out.println(ii);%></option>
<%
}
%>
</select>
月 </font>
<input type="submit" value="查询" name="B1">
</p>
</form>
</td></td></table>
<div align="left">
<left>
<table border="0" width="640">
<tr>
<td align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期日</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期一</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期二</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期三</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期四</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期五</b></font></td>
<td width="14%" align="center" bgcolor="#004F8F"><font color="#ffffff"><b>星期六</b></font></td>
</tr>
<%
int day=1;
int line=0;
int s;
String color="#000000";
//while (day<=dd){while (today.get(Calendar.MONTH)==month){
out.println("<tr>");
//for(int jii=Calendar.SUNDAY;jii < week;jii++)
// out.println("<td width=\"14%\" align=\"center\" bgcolor=\"#EEEDDB\"> </td>");
for (s=1;s<=7;s++){
if (k!=0||day>dd){
out.println("<td width=\"14%\" align=\"center\" bgcolor=\"#EEEDDB\"> </td>");
k--;
}else{
//设置字符颜色
switch (s){
case 6:
case 2:
case 3:
case 4:
case 5:
color="#000000";
break;
case 1:
color="#FF0000";
break;
case 7:
color="#008000";
break;
}
//生成中文农历
String chi;
if (md==1){//1日打印月份
if (everymonth[j][0]!=0 && everymonth[j][0]<i)
{
mm=i-1;
}
else
{
mm=i;
}
if (i==everymonth[j][0]+1 && everymonth[j][0]!=0)
chi=mmonth[0]+mmonth[mm];//闰月
else
chi=mmonth[mm]+mmonth[13];
}
else
{
chi=mday[md];
}
out.println("<td width=\"14%\" align=\"center\" bgcolor=\"#EEEDDB\" ><a href=\"rcb_body.jsp?year="+year+"&month="+(month+1)+"&day="+day+"\" target=main><font color=\""+color+"\"><b>"+day+" </b> <b><font size=\"2\">"+chi+"</font></b></font></a></td>");
day++;
today.add(Calendar.DAY_OF_MONTH,1);
//day=today.get(Calendar.DAY_OF_MONTH);
md++;
if (md>everymonth[j][i])
{
md=1;
i++;
}
if ((i>12 && everymonth[j][0]==0)||(i>13 && everymonth[j][0]!=0))
{
i=1;
j++;
}
}
}
out.println("</tr>");
line++;
}
%>
</table>
</left>
</div>
<table width=640><tr><td height="20">
<%
//补足空行for (int l=1;l<=(6-line);l++){
out.println("<table border=\"0\" width=\"100%\">");
out.println("<tr>");
out.println("<td width=\"100%\"><font color=\"#CCFFFF\"></font></td>");
out.println("</tr>");
out.println("</table>");
}
%>
</td></tr>
</table>
</body>
</html>
│ICalendar │
└─────┘
↑
┌─────────┐ ┌─────┐
│CalendarDecorator │ │Calendar │
└─────────┘ └─────┘
↑ ↑
┌─────────┐ ┌─────────┐
│ JCalendar ├──────┤GregorianCalendar │
└─────────┘1 0..1└─────────┘
public interface ICalendar {
/** 元号の取得 */
public String getGengou();/** 年の取得 */
public int getYear();/** 月の取得 */
public int getMonth();/** 日の取得 */
public int getDay();/** 元号,年月日をセット */
public void set(String gengou, int year, int month, int day); /** 西暦の年月日をセット */
public void set(int year, int month, int date);
}
* GregorianCalendarDecorator.java
* GregorianCalendarデコレーター抽象クラス
*/
public abstract class CalendarDecorator implements ICalendar {
/** 内部状態 GregorianCalendar */
protected GregorianCalendar _gcal; /** _gcalに現在時刻を生成してセット */
protected void _setup() {
_gcal = new GregorianCalendar();
} /** _gcalをセット */
protected void _setup(GregorianCalendar gcal) {
_gcal = gcal;
}/** _gcalを年、月、日から生成してセット
* GregorianCalendarは,1月が0で表されるため,引数の月数から1を引いて生成
* @param year 年
* @param month 月
* @param day 日
*/
protected void _setup(int year, int month, int day) {
_gcal = new GregorianCalendar(year , month-1, day);
}/** _gcalを元号,年、月、日から生成してセット
* サブクラスで実装
* @param gengou 元号
* @param year 年
* @param month 月
* @param day 日
*/
protected abstract void _setup(String gengou, int year, int month, int day); /** 元号の取得 */
public abstract String getGengou();/** 年の取得 */
public abstract int getYear();/** 月の取得 */
public int getMonth() {
return _gcal.get(GregorianCalendar.MONTH)+1;
}/** 日の取得 */
public int getDay() {
return _gcal.get(GregorianCalendar.DAY_OF_MONTH);
} /**
* GregorianCalendarのgetに転送する
* @param field java.util.GregorianCalendarのフィールド
* @return int
*/
public int get(int field) {
if(_gcal != null)
return _gcal.get(field);
else
return 0;
} /** 有効かどうかのチェック
* @return boolean
*/
public boolean isValid() {
if( _gcal != null) return true;
else return false;
} /**
* 元号,年月日をセット
* subClassで実装する
* @param gengou 元号
* @param year 年
* @param month 月
* @param day 日
*/
public abstract void set(String gengou, int year, int month, int day); /** 西暦の年月日をセット
* @param year 年
* @param month 月
* @param day 日
*/
public void set(int year, int month, int date) {
_gcal.set(year, month-1, date);
}
}
/** 和暦チェック
* @param gengou 元号
* @param year 年
* @param month 月
* @param day 日
*/
public static boolean check(String gengou, int year, int month, int day) {
char[] cr = gengou.toCharArray();
char c = cr[0]; if(c!='M' && c!='T' && c!='S' && c!='H') {
return false;
}
CDate cd = new CDate(year, month, day);
if(year < 0) return false;
if(gengou.equals(MEIJI)) {
if(cd.compareTo(fm) == -1 || cd.compareTo(lm) == 1) return false;
}
else if(gengou.equals(TAISHO)) {
if(cd.compareTo(ft) == -1 || cd.compareTo(lt) == 1) return false ;
}
else if(gengou.equals(SHOWA)) {
if(cd.compareTo(fs) == -1 || cd.compareTo(ls) == 1) return false ;
}
else if(gengou.equals(HEISEI)) {
if(cd.compareTo(fh) == -1 ) return false ;
}
return true;
}
/** 元号を取得
* @return String
*/
public String getGengou() {
if(_gcal == null) return ""; if(_gcal.after(LAST_DAY_OF_SHOWA)) return HEISEI;
else if(_gcal.after(LAST_DAY_OF_TAISHO)) return SHOWA;
else if(_gcal.after(LAST_DAY_OF_MEIJI)) return TAISHO;
else if(_gcal.after(LAST_DAY_OF_LUNAR)) return MEIJI;
else return UNSUPPORTED;
}
/** 和暦の年を取得
* @return int
*/
public int getYear() {
if(_gcal==null) return 0;
if(_gcal.after(LAST_DAY_OF_SHOWA)) return _gcal.get(GregorianCalendar.YEAR)-YEAR_HEISEI;
else if(_gcal.after(LAST_DAY_OF_TAISHO)) return _gcal.get(GregorianCalendar.YEAR)-YEAR_SHOWA;
else if(_gcal.after(LAST_DAY_OF_MEIJI)) return _gcal.get(GregorianCalendar.YEAR)-YEAR_TAISHO;
else if(_gcal.after(LAST_DAY_OF_LUNAR)) return _gcal.get(GregorianCalendar.YEAR)-YEAR_MEIJI;
else return 0;
}
/**
* 元号,年月日をセット
* @param gengou 元号
* @param year 年
* @param month 月
* @param day 日
*/
public void set(String gengou, int year, int month, int day) {
if(gengou.equals(HEISEI))
_gcal.set(year+YEAR_HEISEI, month, day);
if(gengou.equals(SHOWA))
_gcal.set(year+YEAR_SHOWA, month, day);
if(gengou.equals(TAISHO))
_gcal.set(year+YEAR_TAISHO, month, day);
if(gengou.equals(MEIJI))
_gcal.set(year+YEAR_MEIJI, month, day);
}/** GYY/MM/DD形式のStringに変換。 */
public String toString() {
return getGengou()+Integer.toString(getYear())+"/"+Integer.toString(getMonth())+"/"+Integer.toString(getDay());
}
/** YY/MM/DD形式のStringに変換。 */
public String toEString() {
return Integer.toString(get(GregorianCalendar.YEAR))+"/"+Integer.toString(getMonth())+"/"+Integer.toString(getDay());
}/** 元号YY年MM年DD日のStringに変換 */
public String toJString() {
String KG = "";
if(getGengou().equals(MEIJI)) {
KG = "明治";
}
else if(getGengou().equals(TAISHO)) {
KG = "大正";
}
else if(getGengou().equals(SHOWA)) {
KG = "昭和";
}
else if(getGengou().equals(HEISEI)) {
KG = "平成";
}
int year = getYear();
String jyear = "";
if(year == 1) {
jyear = "元";
} else {
jyear = Integer.toString(year);
}
return KG+jyear+"年"+Integer.toString(_gcal.get(GregorianCalendar.MONTH)+1)+"月"+Integer.toString(_gcal.get(GregorianCalendar.DAY_OF_MONTH))+"日";
}public static void main(String[] args) {
JCalendar jc = new JCalendar();
System.out.println("Today "+jc);
System.out.println("Today "+jc.toJString()); jc = new JCalendar("00010203");
System.out.println("00010203 "+jc);
System.out.println("00010203 "+jc.toEString()); jc = new JCalendar("19890203");
System.out.println("19890203 "+jc); jc = new JCalendar("19890107");
System.out.println("19890107 "+jc); jc = new JCalendar("S",64,1,7);
System.out.println("S 64 1 7 "+jc); jc = new JCalendar("H",1,1,8);
System.out.println("H 1 1 8 "+jc); jc = new JCalendar(1989,1,8);
System.out.println("1989 1 8 "+jc); jc = new JCalendar("S",20,8,15);
System.out.println("S 20 8 15 "+jc);
System.out.println(jc.toJString());
jc = new JCalendar("T111209");
System.out.println("T111209 "+jc);
System.out.println("T111209 "+jc.toJString()); jc.set(2001,8,11);
System.out.println("2001 8 11 "+jc);
System.out.println("2001 8 11 "+jc.toJString());
}
}
import java.io.*;
import java.net.*;
import java.util.*;
// main() 方法启动代理服务器。具体由内嵌的Proxy类实现
public class ProxyServer {
public static void main(String[] args) {
try {
// 检查args参数数
if ((args.length == 0) || (args.length % 3 != 0))
throw new IllegalArgumentException("Wrong number of args");
// 创建Server对象
Server s = new Server(null, 12);
// 对每个循环创建一个 Proxy并把它添加到 server.
int i = 0;
while(i < args.length) {
String host = args[i++];
int remoteport = Integer.parseInt(args[i++]);
int localport = Integer.parseInt(args[i++]);
s.addService(new Proxy(host, remoteport), localport);
}
}
catch (Exception e) { // 若出错打印错误信息
System.err.println(e);
System.err.println("Usage: java ProxyServer " +"<host> <remoteport> <localport> ...");
System.exit(1);
}
}// 接下来是一个实现了代理服务的类。当有客户端连接时调用serve()方法
// 此时必须首先建立一个连接并在客户和服务器端之间传输数据
// 这个类实现了两个相似线程作为匿名类, 一个线程从客户端拷贝数据到服务器端
// 另一个从服务器端到客户端拷贝数据。线程调用serve()方法创建和启动这些线程,然后等待
// 它们退出
public static class Proxy implements Server.Service {
String host;
int port;// 记住代理的主机和端口
public Proxy(String host, int port) {
this.host = host;
this.port = port;
}
// 当有一个客户端连接时服务器端调用这个方法
public void serve(InputStream in, OutputStream out) {
final InputStream from_client = in;
final OutputStream to_client = out;
final InputStream from_server;
final OutputStream to_server;
// 建立到某一个服务器端端口的连接并返回出错信息
final Socket server;
try {
server = new Socket(host, port);
from_server = server.getInputStream();
to_server = server.getOutputStream();
}
catch (Exception e) {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
pw.print("Proxy server could not connect to " + host +":" + port + "\n");
pw.flush();
pw.close();
try { in.close(); } catch (IOException ex) {}
return;
}
// 建立一个数组保存两个线程。
final Thread[] threads = new Thread[2];
// 建立一个线程从客户端到服务器端拷贝数据
Thread c2s = new Thread() {
public void run() {
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_client.read(buffer))!=-1) {
to_server.write(buffer, 0, bytes_read);
to_server.flush();
}
}
catch (IOException e) {}
finally {
// 当线程任务结束时
try {
server.close();
to_client.close();
from_client.close();
}
catch (IOException e) {}
}
}
};
// 建立一个线程从服务器端到客户端拷贝数据.
// 这些线程和上面那个工作机理一样
Thread s2c = new Thread() {
public void run() {
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_server.read(buffer))!=-1) {
to_client.write(buffer, 0, bytes_read);
to_client.flush();
}
}
catch (IOException e) {}
finally {
try {
server.close(); // 关闭服务器
to_client.close();
from_client.close();
} catch (IOException e) {}
}
}
};
// 把线程保存在 threads[]数组中以便匿名类之间可以相互引用
threads[0] = c2s; threads[1] = s2c;
// 启动线程
c2s.start(); s2c.start();
// 等待他们退出
try { c2s.join(); s2c.join(); } catch (InterruptedException e) {}
}
}
}// 下面的多线程server类框架,实现对端口的监听和数据传输的实时控制
class Server { // 定义Server 类
// server的状态量
Map services;
Set connections;
int maxConnections;
ThreadGroup threadGroup;
PrintWriter logStream;
public Server(OutputStream logStream, int maxConnections) { // 构造函数
setLogStream(logStream);
log("Starting server"); // 记录日志信息
threadGroup = new ThreadGroup(Server.class.getName());
this.maxConnections = maxConnections;
services = new HashMap();
connections = new HashSet(maxConnections);
}// 一个公共的方法 来设置当前登陆流,传递null来关闭登陆
public synchronized void setLogStream(OutputStream out) {
if (out != null) logStream = new PrintWriter(out);
else logStream = null;
}// 记录日志函数
protected synchronized void log(String s) {
if (logStream != null) {
logStream.println("[" + new Date() + "] " + s);
logStream.flush();
}
}protected void log(Object o) { log(o.toString()); } // 把某个对象object写入log// 使server在特定端口开特定服务
public synchronized void addService(Service service, int port) throws IOException
{
Integer key = new Integer(port);
// 检查在某个端口是否已经有其它service
if (services.get(key) != null)
throw new IllegalArgumentException("端口 " + port +" 已经被使用.");
// 创建监听类来监听端口的连接情况
Listener listener = new Listener(threadGroup, port, service);
// 保存在哈希表中
services.put(key, listener);
// 写log
log("启动服务: " + service.getClass().getName() + " 端口为: " + port);
// 开始监听
listener.start();
}// 使server停止某个端口上的服务
public synchronized void removeService(int port) {
Integer key = new Integer(port); // 哈希表关键字
// 在哈希表中查找对某个端口的监听对象
final Listener listener = (Listener) services.get(key);
if (listener == null) return;
// 使得监听器停止
listener.pleaseStop();
// 从哈希表中删除
services.remove(key);
// 写log.
log("停止服务: " + listener.service.getClass().getName() + " 端口: " + port);
}
}// 下面是一个监听器,它监听来自某一个特定端口的连接。
// 当它获得一个连接请求时,它调用服务器的addConnection()方法来接受或拒绝连接
public class Listener extends Thread {
ServerSocket listen_socket; // 监听连接的套接字
int port; // 端口
Service service; // 在端口上实现的服务
volatile boolean stop = false; // 标志是否被请求停止
// 创建一个服务器套接字来监听某个特定端口的连接
public Listener(ThreadGroup group, int port, Service service) throws IOException
{
super(group, "Listener:" + port);
listen_socket = new ServerSocket(port);
// 给出一个非零超时信号使得accept()被中断
listen_socket.setSoTimeout(600000);
this.port = port;
this.service = service;
}// 停止接收连接
public void pleaseStop() {
this.stop = true; // 设置停止标志位
this.interrupt(); // 停止阻断accept()
try { listen_socket.close(); } // 停止监听.
catch(IOException e) {}
}
// 等待连接请求,接受,接着把socket传给sever的addConnection方法
public void run() {
while(!stop) { // 循环直到要求停止
try {
Socket client = listen_socket.accept();
addConnection(client, service);
}
catch (InterruptedIOException e) {}
catch (IOException e) {log(e);}
}
}// 当接受客户端连接以后这个方法将会被监听器调用
// 或者创建一个连接类,或者把这个连接加入到现有的连接列表中,抑或关闭连接
protected synchronized void addConnection(Socket s, Service service) {
// 如果到达连接上限
if (connections.size() >= maxConnections) {
try {
// 则告诉客户端正在被拒绝.
PrintWriter out = new PrintWriter(s.getOutputStream());
out.print("连接被拒绝; " +"服务器忙,请稍后再试.\n");
out.flush();
//关闭连接
s.close();
// 写log
log("连接被拒绝:" +s.getInetAddress().getHostAddress() +
":" + s.getPort() + ": 达到最大连接数.");
} catch (IOException e) {log(e);}
}
// 创建一个线程处理连接
Connection c = new Connection(s, service);
// 并把它添加到当前连接列表中
connections.add(c);
// 把这个新的连接写入log
log("Connected to " + s.getInetAddress().getHostAddress() +":" + s.getPort() + " on port " +
s.getLocalPort() +" for service " + service.getClass().getName());
// 开始连接线程提供服务
c.start();
}
}// 在连接线程退出前调用这个函数,它把某个特定线程从线程列表中删除
protected synchronized void endConnection(Connection c) {
connections.remove(c);
log("连接到: " + c.client.getInetAddress().getHostAddress() +":" + c.client.getPort() + " 关闭.");
}// 改变现有的连接上限
public synchronized void setMaxConnections(int max) {
maxConnections = max;
}// 显示server信息
public synchronized void displayStatus(PrintWriter out) {
// 显示所有服务的列表
Iterator keys = services.keySet().iterator();
while(keys.hasNext()) {
Integer port = (Integer) keys.next();
Listener listener = (Listener) services.get(port);
out.print("SERVICE " + listener.service.getClass().getName()+ " ON PORT " + port +
"\n");
}
// 显示现有连接上限
out.print("MAX CONNECTIONS: " + maxConnections + "\n");
// 显示现有连接列表
Iterator conns = connections.iterator();
while(conns.hasNext()) {
Connection c = (Connection)conns.next();
out.print("连接: " +c.client.getInetAddress().getHostAddress() +
":" + c.client.getPort() + " 端口:" +c.client.getLocalPort() +
c.service.getClass().getName() + "\n");
}
}
}public class Connection extends Thread { // 多线程连接类
Socket client; //与客户端对话的套接字
Service service; //提供给客户端的servicepublic Connection(Socket client, Service service) {// 构造函数
super("Server.Connection:" +client.getInetAddress().getHostAddress() +
":" + client.getPort());
this.client = client;
this.service = service;
}// 把客户端的输入输出流传给某个Service对象的 serve()方法
public void run() {
try {
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
service.serve(in, out);
}
catch (IOException e) {log(e);}
finally { endConnection(this); }
}
}public interface Service {
public void serve(InputStream in, OutputStream out) throws IOException;
}// 一个简单的service,它向客户端显示当前sever上的时间并负责关闭客户端连接
public static class Time implements Service {
public void serve(InputStream i, OutputStream o) throws IOException {
PrintWriter out = new PrintWriter(o);
out.print(new Date() + "\n");
out.close();
i.close();
}
}// 这是另外一个简单的service. 它从客户端读入输入行,然后发送回去然后反转
// 同时显示欢迎信息,当用户键入'.'作为一行的结尾时关闭连接
public static class Reverse implements Service {
public void serve(InputStream i, OutputStream o) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(i));
PrintWriter out =new PrintWriter(new BufferedWriter(new OutputStreamWriter(o)));
out.print("Welcome to the line reversal server.\n");
out.print("Enter lines. End with a '.' on a line by itself.\n");
for(;;) {
out.print("> ");
out.flush();
String line = in.readLine();
if ((line == null) || line.equals(".")) break;
for(int j = line.length()-1; j >= 0; j--)
out.print(line.charAt(j));
out.print("\n");
}
out.close();
in.close();
}
}
public static class HTTPMirror implements Service {
public void serve(InputStream i, OutputStream o) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(i));
PrintWriter out = new PrintWriter(o);
out.print("HTTP/1.0 200 \n");
out.print("Content-Type: text/plain\n\n");
String line;
while((line = in.readLine()) != null) {
if (line.length() == 0) break;
out.print(line + "\n");
}
out.close();
in.close();
}
}public static class UniqueID implements Service {
public int id=0;
public synchronized int nextId() { return id++; }
public void serve(InputStream i, OutputStream o) throws IOException {
PrintWriter out = new PrintWriter(o);
out.print("You are client #: " + nextId() + "\n");
out.close();
i.close();
}
}// 解析一个基于命令的协议,通过这个协议可以提供具有密码保护的对服务的实时控制
public static class Control implements Service {
Server server;
String password;
boolean connected = false; // 是否有某个客户连接
// 创建一个新的控制服务,它将控制某个特定的Server对象, 并需要
// 密码验证以获取相关权限,注意这个Service的构造器包含参数
public Control(Server server, String password) {
this.server = server;
this.password = password;
}// 这是负责提供服务的方法,它读入客户端的命令行,并解析为相关命令和参数
public void serve(InputStream i, OutputStream o) throws IOException {
// 创建流
BufferedReader in = new BufferedReader(new InputStreamReader(i));
PrintWriter out = new PrintWriter(o);
String line;
// 用户是否已提供密码?
boolean authorized = false;
// 如果已经有一个客户端连接,则向客户端发送一个消息并关闭连接
// 在此使用一个synchronized区段来防止资源竞争
synchronized (this) {
if (connected) {
out.print("ONLY ONE CONTROL CONNECTION ALLOWED.\n");
out.close();
return;
}
else
connected = true;
}// 这是主循环:读取一条命令,然后解析处理
for (; ; ) { // 无限循环
out.print("> ");
out.flush();
line = in.readLine(); // 获取用户输入
if (line == null)
break; // 如果 EOF则退出
try {
// 使用StringTokenizer来解析用户命令
StringTokenizer t = new StringTokenizer(line);
if (!t.hasMoreTokens())
continue; //如果输入为空
// 获得输入的第一个词并转换成小写
String command = t.nextToken().toLowerCase();
// 与可能的各种命令比较并执行相应操作
if (command.equals("password")) {
String p = t.nextToken(); // 获取下一个
if (p.equals(this.password)) { // 密码是否正确
out.print("OK\n");
authorized = true; // 授予权限
}
else
out.print("INVALID PASSWORD\n"); // 否则失败
}
else if (command.equals("add")) {
// 检查是否提供了密码
if (!authorized)
out.print("PASSWORD REQUIRED\n");
else {
// 获得服务的名称并尝试动态载入、实例化并处理异常
String serviceName = t.nextToken();
Class serviceClass = Class.forName(serviceName);
Service service;
try {
service = (Service) serviceClass.newInstance();
}
catch (NoSuchMethodError e) {
throw new IllegalArgumentException(
"Service must have a " +
"no-argument constructor");
}
int port = Integer.parseInt(t.nextToken());
// 如果没有产生异常,则添加服务
server.addService(service, port);
out.print("SERVICE ADDED\n"); // 确认
}
}
else if (command.equals("remove")) {
if (!authorized)
out.print("PASSWORD REQUIRED\n");
else {
int port = Integer.parseInt(t.nextToken());
server.removeService(port); // 取消服务
out.print("SERVICE REMOVED\n");
}
}
else if (command.equals("max")) { // 设置连接上限
if (!authorized)
out.print("PASSWORD REQUIRED\n");
else {
int max = Integer.parseInt(t.nextToken());
server.setMaxConnections(max);
out.print("MAX CONNECTIONS CHANGED\n"); //确认
}
}
else if (command.equals("status")) { // 显示状态
if (!authorized)
out.print("PASSWORD REQUIRED\n");
else
server.displayStatus(out);
}
else if (command.equals("help")) { // 帮助命令
// 显示命令语法,不需要密码
out.print("COMMANDS:\n" + "\tpassword <password>\n" +
"\tadd <service> <port>\n" + "\tremove <port>\n" +
"\tmax <max-connections>\n" + "\tstatus\n" + "\thelp\n" +
"\tquit\n");
}
else if (command.equals("quit"))
break;
else
out.print("UNRECOGNIZED COMMAND\n"); // 出现错误
}
catch (Exception e) {
out.print("ERROR WHILE PARSING OR EXECUTING COMMAND:\n" + e + "\n");
}
}
// 关闭流并把连接标志位设为false使得其它客户端连接
connected = false;
out.close();
in.close();
}
}
import java.net.*;
public class URLClient {
protected URLConnection connection;
public static void main(String[] args) {
URLClient client = new URLClient();
String yahoo = client.getDocumentAt("http://192.168.34.127:8080/openwiki/"); //path
System.out.println(yahoo);
}public String getDocumentAt(String urlString) {
StringBuffer document = new StringBuffer();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
reader.close();
} catch (MalformedURLException e) {
System.out.println("Unable to connect to URL: " + urlString);
} catch (IOException e) {
System.out.println("IOException when connecting to URL: " + urlString);
}
return document.toString(); }
}
import java.text.DecimalFormat;public class CMoneyUtil {
private static char[] big = {
'亿', '仟', '佰', '拾', '兆', '万', '仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟',
'佰', '拾', '元', '角', '分'
};
private static char[] num = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
public final static int LONG = 1;
public final static int INTEGER = 2;
public final static int HUNMAN_READING = 4;
public static String toCurrency(double value, int flag) {
String ret = ""; if (value < 0.005) {
ret = "数字太小,无法转换";
} else {
DecimalFormat df = new DecimalFormat("#.00");
ret = df.format(value); int index = ret.length();
ret = ret.substring(0, index - 3) + ret.substring(index - 2); char[] buf = ret.toCharArray(); int p = 0; while (buf[p] == '0')
p++; char[] tmp = new char[buf.length - p]; for (int i = 0; p < buf.length; i++, p++)
tmp[i] = buf[p]; buf = tmp;
index = buf.length; // System.out.println(buf);
StringBuffer sb = new StringBuffer(40);
int off = big.length - index; int uni = 0; // 持续为零标志
for (int i = 0; i < index; i++,off ++) {
int c = buf[i] - '0'; if (((flag & LONG) != 0) || (c != 0)) {
if(c != 1 ){
sb.append(num[c]);
sb.append(big[off] );
} else if ( (off == 3 )|| (off == 8 )|| (off == 12 )|| (off == 17 )){
sb.append(big[off ]);
} else {
sb.append(num[c]);
sb.append(big[off ]);
}
uni ++;
if (( off == 4 ) || ( off == 9 ) || ( off == 13)) {
uni = 0;
}
// 元 什么时候都会有该单位
} else if ( off == 17 ) {
sb.append(big[off ]);
// 兆 亿 万
} else if (( off == 4 ) || ( off == 9 ) || ( off == 13)) {
if(uni > 0){
sb.append(big[off]);
if( (flag & HUNMAN_READING) != 0){
sb.append("零");
}
} else {
if( (flag & HUNMAN_READING) != 0){
sb.append("零");
}
}
uni = 0;
}
} ret = sb.toString();
} return ret;
} public static String toCNumber(double value){
String ret = ""; DecimalFormat df = new DecimalFormat();
ret = df.format(value); int index = ret.length(); char[] buf = ret.toCharArray(); int p = 0; while (buf[p] == '0')
p++; char[] tmp = new char[buf.length - p]; for (int i = 0; p < buf.length; i++, p++)
tmp[i] = buf[p]; buf = tmp;
index = buf.length; // System.out.println(buf);
StringBuffer sb = new StringBuffer(40);
int off = big.length - index; for (int i = 0; i < index; i++) {
int c = buf[i] - '0';
sb.append(num[c]);
sb.append(big[off + i]);
} ret = sb.toString();
return ret;
} private static char[] swapArray(char[] array) {
int l = array.length;
char[] ret = new char[l]; for (int i = 0; i < ret.length; i++) {
ret[i] = array[l - i - 1];
} return ret;
} public static void test3(){
System.out.println(CMoneyUtil.toCNumber(0)); // 零
System.out.println(CMoneyUtil.toCNumber(0.1)); // 零点壹
System.out.println(CMoneyUtil.toCNumber(0.02)); // 零点零贰
System.out.println(CMoneyUtil.toCNumber(430)); // 肆佰叁拾
System.out.println(CMoneyUtil.toCNumber(9503)); // 玖仟伍佰零叁
System.out.println(CMoneyUtil.toCNumber(10503)); // 壹万零伍佰零叁
System.out.println(CMoneyUtil.toCNumber(60003)); // 陆万零叁
System.out.println(CMoneyUtil.toCNumber(20.2)); // 贰拾点贰
System.out.println(CMoneyUtil.toCNumber(123456789.123456789)); // 壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖点壹贰叁肆伍陆柒捌玖7
}
public static void test1() {
System.out.println(CMoneyUtil.toCurrency(0, 1));
System.out.println(CMoneyUtil.toCurrency(0.001, 1));
System.out.println(CMoneyUtil.toCurrency(0.1, 1));
System.out.println(CMoneyUtil.toCurrency(0.02, 1));
System.out.println(CMoneyUtil.toCurrency(2, 1));
System.out.println(CMoneyUtil.toCurrency(3.1, 1));
System.out.println(CMoneyUtil.toCurrency(224, 1));
System.out.println(CMoneyUtil.toCurrency(2230.63, 1));
System.out.println(CMoneyUtil.toCurrency(223.636, 1));
System.out.println(CMoneyUtil.toCurrency(223.634, 1));
} public static void test2() {
System.out.println(CMoneyUtil.toCurrency(0, 2));
System.out.println(CMoneyUtil.toCurrency(0.001, 2));
System.out.println(CMoneyUtil.toCurrency(0.1, 2));
System.out.println(CMoneyUtil.toCurrency(0.02, 2));
System.out.println(CMoneyUtil.toCurrency(2, 2));
System.out.println(CMoneyUtil.toCurrency(3.1, 2));
System.out.println(CMoneyUtil.toCurrency(4.07, 2));
System.out.println(CMoneyUtil.toCurrency(500, 2));
System.out.println(CMoneyUtil.toCurrency(224, 2));
System.out.println(CMoneyUtil.toCurrency(2230.63, 2));
System.out.println(CMoneyUtil.toCurrency(223.636, 2));
System.out.println(CMoneyUtil.toCurrency(223.634, 2));
System.out.println(CMoneyUtil.toCurrency(1201223.634, 2));
System.out.println(CMoneyUtil.toCurrency(2000001223.634, 2));
System.out.println(CMoneyUtil.toCurrency(Double.parseDouble("60000000101223.634"), HUNMAN_READING));
} public static void main(String[] argv) {
test2(); // System.out.println((int)'0');
// System.out.println((int)'9');
}
}
import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;public class DateDiff{
public static void main(String[] args){
String s1= "20040301";
String s2="20040330";
DateFormat df1 = new SimpleDateFormat("yyyyMMDD");
Date date1=new Date();
Date date2=new Date();
String strResult="";
Calendar d1=Calendar.getInstance();
Calendar d2=Calendar.getInstance(); try{
date1= df1.parse(s1) ;
date2= df1.parse(s2) ;
d1.setTime(date1);
d2.setTime(date2);
long result;
result=dateDiff("DAY",d1,d2);
strResult=String.valueOf(result);
}catch(ParseException e){ }
System.out.println(strResult);
}
public static long dateDiff(String part, Calendar startCal, Calendar endCal) {
long deltaMs = endCal.getTimeInMillis() - startCal.getTimeInMillis(); if ("MILLISECOND".equalsIgnoreCase(part)) {
return deltaMs;
} int reverse = 1;
//if start time is after the end time
if(startCal.after(endCal)){
reverse = -1;
deltaMs = -deltaMs;
Calendar tmp = startCal;
startCal = endCal;
endCal = tmp;
} long res = 0; if ("YEAR".equalsIgnoreCase(part)) {
res = endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
} else if ("MONTH".equalsIgnoreCase(part)) {
int year = endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
res += year * 12;
res += endCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH);
} else if ("WEEK".equalsIgnoreCase(part)) {
res += deltaMs / (7 * 24 * 3600 * 1000);
int w = startCal.get(Calendar.DAY_OF_WEEK);
int tmp = (int)(deltaMs % (7*24*3600*1000));
startCal.add(Calendar.MILLISECOND,tmp);
int w2 = startCal.get(Calendar.DAY_OF_WEEK);
if(w2<w || (w2 == w && tmp>(24*3600*1000))){
res++;
}
} else{
long base = 0;
int type = 0;
if ("DAY".equalsIgnoreCase(part)) {
type = Calendar.DATE;
base = 24 * 3600 * 1000;
} else if ("HOUR".equalsIgnoreCase(part)) {
type = Calendar.HOUR;
base = 3600 * 1000;
} else if ("MINUTE".equalsIgnoreCase(part)) {
type = Calendar.MINUTE;
base = 60 * 1000;
} else if ("SECOND".equalsIgnoreCase(part)) {
type = Calendar.SECOND;
base = 1000;
}else{
return Long.MIN_VALUE;
}
int cur = startCal.get(type);
res = deltaMs / base;
int tmp = (int)(deltaMs % base);
startCal.add(Calendar.MILLISECOND,tmp);
if(startCal.get(type)!=cur){
res++;
}
}
return res*reverse;
}
}