Excel日期/時間儲存數值轉換為具體日期/時間(java實現)
阿新 • • 發佈:2019-01-24
在用POI的事件模型eventusermodel讀取大容量Excel時發現讀取的日期、時間格式輸出後是浮點數字符串,然而沒有找到有類似於usermodel的分格式讀取的方法,於是編寫一個工具類,把獲取的浮點數轉換成日期/時間格式,增加可用性。
Excel用浮點數標記日期時間,整數位代表日期,小數位代表時間。
程式碼如下:
package Util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Created by yijie on 9/15/16.
*/
public class StringToDate {
private static final int SECONDS_PER_MINUTE = 60;
private static final int MINUTES_PER_HOUR = 60;
private static final int HOURS_PER_DAY = 24;
private static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);
/**
一天的毫秒數
**/
private static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L;
private static SimpleDateFormat sdFormat;
/**
轉換方法
@parma numberString 要轉換的浮點數
@parma format 要獲得的格式 例如"hh:mm:ss"
**/
public static String toDate(double numberString, String format) {
sdFormat = new SimpleDateFormat(format);
int wholeDays = (int)Math.floor(numberString);
int millisecondsInday = (int)((numberString - wholeDays) * DAY_MILLISECONDS + 0.5);
Calendar calendar = new GregorianCalendar();
setCalendar(calendar, wholeDays, millisecondsInday, false);
return sdFormat.format(calendar.getTime());
}
private static void setCalendar(Calendar calendar, int wholeDays,
int millisecondsInDay, boolean use1904windowing) {
int startYear = 1900;
int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
if (use1904windowing) {
startYear = 1904;
dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
}
else if (wholeDays < 61) {
// Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
// If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
dayAdjust = 0;
}
calendar.set(startYear,0, wholeDays + dayAdjust, 0, 0, 0);
calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay);
}
}