根据系统毫秒数计算年月日时分秒,只允许通过四则运算
http://yy629.iteye.com yyong629@qq.com 日期: 2012年04月25日
[color=darkblue]
看到别人写的结果不正确, 就花些时间自己做了一个.
简单测试了, 没有
发现错误, 基本上应该是正确的了.
[小弟不才,也闲着蛋疼,写的比较凌乱.]
public static String myTimeStr(long timeMillis) {
int timezone = 8;
long totalSeconds = timeMillis / 1000;
totalSeconds += 60 * 60 * timezone;
int second = (int)(totalSeconds % 60);// 秒
long totalMinutes = totalSeconds / 60;
int minute = (int)(totalMinutes % 60);// 分
long totalHours = totalMinutes / 60;
int hour = (int)(totalHours % 24);// 时
int totalDays = (int)(totalHours / 24);
int _year = 1970;
int year = _year + totalDays / 366;
int month = 1;
int day = 1;
int diffDays;
boolean leapYear;
while (true) {
int diff = (year - _year) * 365;
diff += (year - 1) / 4 - (_year - 1) / 4;
diff -= ((year - 1) / 100 - (_year - 1) / 100);
diff += (year - 1) / 400 - (_year - 1) / 400;
diffDays = totalDays - diff;
leapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
if (!leapYear && diffDays < 365 || leapYear && diffDays < 366) {
break;
} else {
year++;
}
}
int[] monthDays;
if (diffDays >= 59 && leapYear) {
monthDays = new int[]{-1,0,31,60,91,121,152,182,213, 244, 274, 305, 335 };
} else {
monthDays = new int[]{-1,0,31,59,90,120,151,181,212, 243, 273, 304, 334 };
}
for (int i = monthDays.length - 1; i >= 1; i--) {
if (diffDays >= monthDays[i]) {
month = i;
day = diffDays - monthDays[i] + 1;
break;
}
}
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
// 以下是测试代码
public static void main(String[] args) throws Exception {
long curr = System.currentTimeMillis(); // *10
for (long i = 0; i <= curr; i += 1000L * 60 * 30) {//*60*12
String a = jdkTimeStr(i);
String b = myTimeStr(i);
if (!a.equals(b)) {
System.out.println(">>>>>>>>> " + i + ": " + a + " " + b);
// break;
} else {
//System.out.println(i + ": " + a + " " + b);
}
}
}
public static String jdkTimeStr(long timeMillis) { // 通过jdk日期类获取
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
c.setTimeInMillis(timeMillis);
return c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " "
+ c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
}