根据函数System.currentTimeMillis()返回的毫秒数得到日期

本文介绍了如何利用Java中的System.currentTimeMillis()方法获取当前时间的毫秒数,并将其转换为日期对象进行显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//计算自1970年1月1日 ,根据函数System.currentTimeMillis()返回的毫秒数得到日期
class ch0533 {
public static void main(String[] args) {
    long ms=System.currentTimeMillis();
    System.out.println(formatTime(ms));

    }
public static String formatTime(long ms) {
         int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  
         int month_days_leap[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  //闰年的月数
             int h1=1000*60*60*8;//东八区所以要加八个小时
         ms+=h1;
         int ss = 1000;
             int mi = ss * 60;
             int hh = mi * 60;
             int dd = hh * 24;
         int mm=1;//一月
         int yy=1970;
         long day = ms / dd;
         long d2=ms/dd;
         d2++;//一号开始算
             for(;;)
         {
        if(isleapyear(yy))
        {   if(d2<366)
            break;
            else {yy++;
                d2-=366;}
        }
        else   {
            if(d2<365)
                break;
            else {yy++;
                d2-=365;}
            }
        }
         for(int i=0;i<12;i++)
         {
        if(isleapyear(yy))
            {   if(d2<month_days_leap[i])
                {mm=i+1;break;}
            else
                d2-=month_days_leap[i];}
        else        
        {   if(d2<month_days[i])
                {mm=i+1;break;}
            else
                d2-=month_days[i];}
        }

             long hour = (ms - day * dd) / hh;
             long minute = (ms - day * dd - hour * hh) / mi;
             long second = (ms - day * dd - hour * hh - minute * mi) / ss;
             long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
             String strHour = hour < 10 ? "0" + hour : "" + hour;
             String strMinute = minute < 10 ? "0" + minute : "" + minute;
             String strSecond = second < 10 ? "0" + second : "" + second;
             String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒
             strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

             return yy+"年"+mm+"月"+d2+"日"+strHour + " 小时 "+strMinute + " 分钟 " + strSecond + " 秒";}






public static boolean isleapyear(int yy)  
{  
    if( (yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0)  
        return true;  
    else  
        return false;  
}  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值