檔案下載
一、在設計日期相關程式時常需要用到日期的轉換,諸如西元轉民國、民國轉西元等,但若每次因為不同的格式需求下,而重新設計各種不同函式的處理方式,這樣雖可行但缺乏效率,且設計時常會忘記運算方式,故此設計一函式能夠將西元與民國相互轉換,並依照個人需求加入格式參數,如此將可轉換多種格式如:
1.西元 2014 年 01 月 15 日要轉成->民國 103 年 01 月 15 日
2.民國 103 年 01 月 15 日要轉成->西元 2014 年 01 月 15 日
3.2013/05/08要轉成->102/05/08
二、主要函式
private String convertTWDate (String AD,String beforeFormat,String afterFormat){//轉年月格式
if (AD == null) return "";
SimpleDateFormat df4 = new SimpleDateFormat(beforeFormat);
SimpleDateFormat df2 = new SimpleDateFormat(afterFormat);
Calendar cal = Calendar.getInstance();
try {
cal.setTime(df4.parse(AD));
if (cal.get(Calendar.YEAR) > 1492) cal.add(Calendar.YEAR, -1911);
else cal.add(Calendar.YEAR, +1911);
return df2.format(cal.getTime());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
三、轉換方式
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.table.DefaultTableModel;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
/**
*
* @author user
*/
public class Test {
public Test(){
System.out.println(convertTWDate("2013/05/08","yyyy/MM/dd","yyyMM"));
System.out.println(convertTWDate("2013/05/08","yyyy/MM/dd","yyyMMdd"));
System.out.println(convertTWDate("2013/05/08","yyyy/MM/dd","yyy/MM/dd"));
System.out.println(convertTWDate("2013/05/08","yyyy/MM/dd","yyy-MM-dd"));
System.out.println(convertTWDate("2013/05/08","yyyy/MM/dd","yy-MM-dd"));
System.out.println(convertTWDate("民國 103 年 01 月 15 日","民國 yyy 年 MM 月 dd 日","西元 yyyy 年 MM 月 dd 日"));
System.out.println(convertTWDate("西元 2014 年 01 月 15 日","西元 yyyy 年 MM 月 dd 日","民國 yyy 年 MM 月 dd 日"));
}
public static void main(String[] args) throws SQLException {
new Test();
}
private String convertTWDate (String AD,String beforeFormat,String afterFormat){//轉年月格式
if (AD == null) return "";
SimpleDateFormat df4 = new SimpleDateFormat(beforeFormat);
SimpleDateFormat df2 = new SimpleDateFormat(afterFormat);
Calendar cal = Calendar.getInstance();
try {
cal.setTime(df4.parse(AD));
if (cal.get(Calendar.YEAR) > 1492) cal.add(Calendar.YEAR, -1911);
else cal.add(Calendar.YEAR, +1911);
return df2.format(cal.getTime());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

留言
張貼留言