Java时间处理相对时间 之 时区相关;
在一些场景下需要取得一个相对时间值,比如取1994年1月1号到当前时间的值,这个值是一个相对值,即:不管在哪个时区,如果是同一个时间获取的值是一样的;
在Java的代码处理上需要注意一下,这里提供一个方法:
1. 思路就是将需要换算的时间转换为同一个时区来进行计算:
/**
* 获取当前时间,相对1994的秒数
* @return int
*/
public static int getSecondFrom1994()
{
int seconds = 0;
try
{
Calendar curDate = Calendar.getInstance();
curDate.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
fmt.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date date_1994 = fmt.parse("1994-01-01 00:00:00");
seconds = (int) ((curDate.getTimeInMillis() - date_1994.getTime()) / 1000);
uniportal_logger.trace("----getSecond1994----:"+seconds);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return seconds;
}
/**
* 根据日期字符串获取相对1994-01-01的秒数
* @param dateStr String
* @return long
*/
public static int getMilSecondFrom1994(String dateStr)
{
int seconds = 0;
if(dateStr == null || dateStr.length() == 0)
{
return seconds;
}
try
{
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
fmt.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date date_1994 = fmt.parse("1994-01-01 00:00:00");
Date date_temp = fmt.parse(dateStr);
seconds = (int) ((date_temp.getTime() - date_1994.getTime()) / 1000);
uniportal_logger.trace("----getMilSecondFrom1994----:"+seconds);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return seconds;
}
/**
*根据相对1994年的秒数,获取应该显示的时间字符串
* @return string
*/
public static String getDate1994(int seconds)
{
int DaysPerYear = 365;
int[] DaysPerMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
int days = seconds / 86400;
int second = seconds % 86400;
int hour = second / 3600;
second = second % 3600;
int minute = second / 60;
second = second % 60;
int dayss = days;
/* compute year */
int year = 1994;
while(days >= DaysPerYear)
{
days -= DaysPerYear;
if((++year % 4) == 0)
DaysPerYear = 366;
else
DaysPerYear = 365;
}
/* compute month */
if((year % 4) == 0)
DaysPerMonth[1] = 29;
else
DaysPerMonth[1] = 28;
int month = 1;
while(days >= DaysPerMonth[month - 1])
{
days -= DaysPerMonth[month - 1];
month++;
}
/* compute date and week */
int day = days + 1;
int week = (dayss + 6) % 7;
if(week == 0)
week = 7;
StringBuffer buf = new StringBuffer();
buf.append(year).append("-");
buf.append(month > 9 ? month : ("0" + month)).append("-");
buf.append(day > 9 ? day : ("0" + day)).append(" ");
buf.append(hour > 9 ? hour : ("0" + hour)).append(":");
buf.append(minute > 9 ? minute : ("0" + minute)).append(":");
buf.append(second > 9 ? second : ("0" + second));
String str = buf.toString().trim();
if("1994-01-01 00:00:00".equals(str))
{
str = "";
}
return str;
}
2. 相关linux命令:
修改时区为美国的: TZ=‘America/Caracas‘; export TZ 有半个小时的差别
修改为中国东八时区的: TZ=‘Asia/Shanghai‘; export TZ 整个时区