您的位置:首页 > 其它

显示当前日期和时间(通过调用System.currentTimeMills ()方法)

2017-02-24 17:29 691 查看
方法System.currentTimeMills ()返回格林威治1970年1月1日00:00:00(UNIX时间戳)开始到当前时刻的毫秒数

代码:

package com.im;

public class Demo624 {

public static void main(String[] args) {
// TODO Auto-generated method stub

//System.currentTimeMillis()返回从GMT1970年1月1日00:00:00开始到当前时刻的毫秒数
long totalMillSeconds = System.currentTimeMillis(); //定义总的毫秒数

long totalSeconds = totalMillSeconds/1000;   //将毫秒数转换为秒数

long currentSeconds = totalSeconds%60;  //取余求的当前的秒

long totalMinutes = totalSeconds/60;  //求出总的分钟数

long currentMinutes = totalMinutes%60;   //取余求当前的分钟

long totalHours = totalMinutes/60;   //求出总的小时数

long currentHours = totalHours%24;  //取余求出当前的小时

int totalDays = (int) (totalHours/24);
if(currentHours > 0){    //当前的小时大于0,则是新的一天
totalDays++;
}

int currentYear = 2000; //假设当前的年份为2000

do{
currentYear++; //如果1970年到2000年总的天数小于totalDays,则当前年份自加
}while(totalDays-getTotalNumsOfDayInYears(currentYear) > 0);


// int currentMonth = 1;

//

// do{

// currentMonth++;

// }while(totalDays > getTotalNumsOfMonths(currentYear, currentMonth));

//

// int currentDay = (totalDays - getTotalNumsOfMonths(currentYear, currentMonth-1));

//定义当前的年中的天数
int totalNumsOfDayInTheYear = totalDays - getTotalNumsOfDayInYears(currentYear-1);

//当前年的天数大于当前年中月份和的天数,月份自增
int currentMonth = 0;
do{
currentMonth++;
}while(totalNumsOfDayInTheYear > getTotalNumsOfMonths(currentYear, currentMonth));

//用当前年的总天数减去求得的总月份的上一个月,得到当前的天数
int currentDay = totalNumsOfDayInTheYear - getTotalNumsOfMonths(currentYear, currentMonth-1);

System.out.println("当前北京时间为:" +currentYear + "/" +
currentMonth + "/" + currentDay + "  "+
(currentHours+8) + ":" + currentMinutes + ":" + currentSeconds);

}

public static int getTotalNumsOfMonths(int year,int month){  //获取当前年份月份的总共天数


// int total = getTotalNumsOfDayInYears(year);

//

// for(int i=1; i<=month; i++){

// total += getNumsOfDayInMonths(year, i);

// }

//

// return total;

int total = 0;
for(int i=1; i<=month; i++){
total += getNumsOfDayInMonths(year, i);
}

return total;
}

public static int getTotalNumsOfDayInYears(int year){  //获取从1970年1月1日到现在的总共年份和的天数

int total = 0; //总共的天数初始化为0
for(int i=1970; i<=year; i++){
if(isLeapYear(i)){
total += 366;
}else{
total += 365;
}
}
return total;
}

public static int getNumsOfDayInMonths(int year,int month){  //获取每个月中的天数

switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
if(isLeapYear(year)){
return 29;
}else{
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
}

return 0; //月份不存在
}

public static boolean isLeapYear(int year){  //判断是否闰年

if(year%4==0 && year%100!=0 || year%400==0){
return true;
}else{
return false;
}
}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  方法 循环
相关文章推荐