时间、日期

 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(date2));
运行结果如下:

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

上面的代码,我在实际用的时候,取几天前的时间没问题,是正确的,,但当相隔天数多的时候,时间就是错误的,不知道为什么(怀疑,按天算时,最小单位应该是秒,不是毫秒?)。后来改为如下就正确了:

long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date = new Date(currentTime);
Date date1 = new Date(currentTime/1000+ 25*24*60*60);
Date date2 = new Date(currentTime/1000 - 25*24*60*60);

System.out.println("当前时间:"+formatter.format(date));
System.out.println("25天后的当前时间:"+formatter.format(date1*1000));
System.out.println("25天前的当前时间:"+formatter.format(date2*1000));

关于System.currentTimeMillis() 参考网址:https://www.cnblogs.com/rinack/p/6776100.html


老项目方法一个例子:

    /**
     * 得到下几天
     * 
     * @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 ( ) ) ;
    }