时间、日期

2022-10-15,

 

 new date();


import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;

//调用 starttime = getnextdate("yyyy-mm-dd 00:00:00",-7);//7天前的日期 /** * 获得 当前时间间隔nday 的日期时间 * @param format 返回时间的格式 yyyy-mm-dd hh:mm:ss * @param nday 间隔的天数 * @return */ public static string getnextdate(string format,int nday) { calendar calendar = calendar.getinstance(); //得到日历 date dnow = new date();//获得当前时间 calendar.settime(dnow);//把当前时间赋给日历 calendar.add(calendar.date, nday); //设置为间隔nday天(eg:-1为前一天,+1为后一天) date dintervaldate = calendar.gettime(); //得到时间 //simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");//设置时间格式 simpledateformat sdf = new simpledateformat(format);//设置时间格式 string time = sdf.format(dintervaldate); //格式化 system.out.println("**********************time="+time); return time; } //当前日期为2019-09-24,运行结果: **********************time=2019-09-17 00:00:00

 

在开发过程中,通常很多人都习惯使用new date()来获取当前时间。new date()所做的事情其实就是调用了system.currenttimemillis()。

如果仅仅是需要或者毫秒数,那么完全可以使用system.currenttimemillis()去代替new date(),效率上会高一点。如果需要在同一个方法里面多次使用new date(),通常性能就是这样一点一点地消耗掉,这里其实可以声明一个引用。

 

 

system.currenttimemillis():

该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和gmt时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数(1s=1000ms)。可以直接把这个方法强制转换成date类型。代码如下:

long currenttime = system.currenttimemillis();
simpledateformat formatter = new simpledateformat("yyyy-mm-dd hh:mm:ss");

date date = new date(currenttime);
date date1 = new date(currenttime+1*60*1000);
date date2 = new date(currenttime-1*24*3600*1000);

system.out.println("当前时间:"+formatter.format(date));
system.out.println("1分钟后的当前时间:"+formatter.format(date1));
system.out.println("1天前的当前时间:"+formatter.format(date1));

运行结果如下:

当前时间:2019-09-24 11:47:30
1分钟后的当前时间:2019-09-24 11:48:30
1天前的当前时间:2019-09-24 11:48:30

关于system.currenttimemillis() 参考网址:

老项目方法一个例子:

    /**
     * 得到下几天
     * 
     * @param tsdate
     *  日期
     */
    static public java.sql.timestamp getnextdate ( java.sql.timestamp tsdate ,
            int nday )
    {
        if (null == tsdate)
            return null ;

        gregoriancalendar calendar = new gregoriancalendar ( ) ;
        calendar.settime ( tsdate ) ;
        calendar.add ( calendar.date , nday ) ;
        java.util.date resdate = calendar.gettime ( ) ;
        return new timestamp ( resdate.gettime ( ) ) ;
    }

 

《时间、日期.doc》

下载本文的Word格式文档,以方便收藏与打印。