码迷,mamicode.com
首页 > 其他好文 > 详细

时间、日期

时间:2019-09-24 15:57:03      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:add   计算   mes   text   24*   null   sim   网址   import   

 

 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() 参考网址: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 ( ) ) ;
    }

 

时间、日期

标签:add   计算   mes   text   24*   null   sim   网址   import   

原文地址:https://www.cnblogs.com/zdyang/p/11578405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!