时间相关小脚本

前言

记录用到过的时间相关小脚本。

一、calendar

1.1calendar设置时间

1、日期加减

//给存储过程的参数设置值
java.util.Date d = new java.util.Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(d);
calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
d = calendar.getTime();//这个时间就是日期往后推一天的结果
java.sql.Date date = new java.sql.Date(d.getTime());//会丢失时分秒
Calendar calendar = new GregorianCalendar();
int currentMonth = calendar.get(Calendar.MONTH )+1;
calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);
calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
int day=calendar.get(Calendar.DAY_OF_MONTH);
int year = calendar.get(Calendar.YEAR);
java.sql.Date date = null;
try {
    date = (Date)new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(year)+"-"+String.valueOf(currentMonth)+"-"+String.valueOf(day));
    //date=(Date)TimeUtils.getDate("yyyy-MM-dd",String.valueOf(year+"-"+currentMonth+"-"+day));
} catch (ParseException e) {
    e.printStackTrace();
    ConnectionUtil.rollBackTransaction(conn);
}

2、java中日期增加指定天数

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
String dateFormat1=sdf.format(date);
System.out.println(dateFormat1);
System.out.println(date);
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 4);
Date date2=calendar.getTime();
System.out.println(date2); 
String dateFormat=sdf.format(date2);
System.out.println(dateFormat);

3、获取业务账单期

1 //业务账单期
2 Calendar c = Calendar.getInstance();
3 int tmpQuarter=(c.get(Calendar.MONTH)+3)/3;
4 fzAcc.setAccWorkPeriod("0" + tmpQuarter +"Q");
5 //账单期(年份)
6 //获取当前的时间,包括毫秒
7 LocalDateTime ldt = LocalDateTime.now();
8 fzAcc.setAccWorkPeriodYear(String.valueOf(ldt.getYear()));

4、Java获取当前时间前一周、前一月、前一年的时间

 1 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 2         Calendar c = Calendar.getInstance();
 3          
 4         //过去七天
 5         c.setTime(new Date());
 6         c.add(Calendar.DATE, - 7);
 7         Date d = c.getTime();
 8         String day = format.format(d);
 9         System.out.println("过去七天:"+day);
10          
11         //过去一月
12         c.setTime(new Date());
13         c.add(Calendar.MONTH, -1);
14         Date m = c.getTime();
15         String mon = format.format(m);
16         System.out.println("过去一个月:"+mon);
17          
18         //过去三个月
19         c.setTime(new Date());
20         c.add(Calendar.MONTH, -3);
21         Date m3 = c.getTime();
22         String mon3 = format.format(m3);
23         System.out.println("过去三个月:"+mon3);
24          
25         //过去一年
26         c.setTime(new Date());
27         c.add(Calendar.YEAR, -1);
28         Date y = c.getTime();
29         String year = format.format(y);
30         System.out.println("过去一年:"+year);
31         
32         
33         import java.text.SimpleDateFormat;
34 import java.util.Calendar;
35 
36 public class Test1 {
37     public static void main(String[] args) {
38         Calendar calendar = Calendar.getInstance();
39         SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
40 
41         // 获取当前日期
42         System.out.println(sdf.format(calendar.getTime()));
43 
44         // 获取一个月前的日期
45         calendar.add(Calendar.MONTH, -1);
46         String endDate = sdf.format(calendar.getTime());
47         System.out.println(endDate);
48     }
49 }

5、Calendar类获取本月的第一天和最后一天,最近3个月的时间范围,本季度,上季度的时间范围

 1 https://blog.csdn.net/qq_33867131/article/details/120505308
 2 
 3 获取近12个月的每月最后一天
 4 public static void main(String[] args) {
 5     SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
 6 
 7     List<AppReinsCockpitPrmLog> appReinsCockpitPrmLogList = new ArrayList<>();
 8     //默认库里存的统计时间为每个月的最后一天
 9     Map<Date, AppReinsCockpitPrmLog> collect = appReinsCockpitPrmLogList.stream().collect(Collectors.toMap(
10             AppReinsCockpitPrmLog::getStatisticalDate,
11             appReinsCockpitPrmLog -> appReinsCockpitPrmLog,
12             (key1, key2) -> key2
13     ));
14     //获取当前时间
15 
16     Calendar calendar=Calendar.getInstance();
17     calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
18     //减一天
19     //calendar.add(Calendar.DATE, -1);
20     String endDate = sdf.format(calendar.getTime());
21     System.out.println(endDate);
22     //加两年
23     calendar.add(Calendar.YEAR,+2);
24     System.out.println(endDate);
25     for (int i =1 ;i<=12; i++) {
26         calendar.add(Calendar.MONTH, -1);
27         calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
28         endDate = sdf.format(calendar.getTime());
29         Date cu = new Date();
30         //System.out.println(cu);
31         Date time = calendar.getTime();
32         //System.out.println(calendar.getTime());
33         System.out.println(endDate);
34     }
35 }

6、Calendar获取当前年份、月份、日期

 1 package com.wenxiaowu.date;
 2 
 3 import org.junit.Test;
 4 
 5 import java.text.SimpleDateFormat;
 6 import java.util.Calendar;
 7 import java.util.Date;
 8 
 9 /**
10  * Calendar获取当前年份、月份、日期
11  */
12 public class CalendarTest {
13     @Test
14     public void test() {
15         Calendar cale = null;
16         cale = Calendar.getInstance();
17         int year = cale.get(Calendar.YEAR);
18         int month = cale.get(Calendar.MONTH) + 1;
19         int day = cale.get(Calendar.DATE);
20         int hour = cale.get(Calendar.HOUR_OF_DAY);
21         int minute = cale.get(Calendar.MINUTE);
22         int second = cale.get(Calendar.SECOND);
23         int dow = cale.get(Calendar.DAY_OF_WEEK);
24         int dom = cale.get(Calendar.DAY_OF_MONTH);
25         int doy = cale.get(Calendar.DAY_OF_YEAR);
26 
27         System.out.println("Current Date: " + cale.getTime());
28         System.out.println("Year: " + year);
29         System.out.println("Month: " + month);
30         System.out.println("Day: " + day);
31         System.out.println("Hour: " + hour);
32         System.out.println("Minute: " + minute);
33         System.out.println("Second: " + second);
34         System.out.println("Day of Week: " + dow);
35         System.out.println("Day of Month: " + dom);
36         System.out.println("Day of Year: " + doy);
37 
38         // 获取当月第一天和最后一天
39         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
40         String firstday, lastday;
41         // 获取前月的第一天
42         cale = Calendar.getInstance();
43         cale.add(Calendar.MONTH, 0);
44         cale.set(Calendar.DAY_OF_MONTH, 1);
45         firstday = format.format(cale.getTime());
46         // 获取前月的最后一天
47         cale = Calendar.getInstance();
48         cale.add(Calendar.MONTH, 1);
49         cale.set(Calendar.DAY_OF_MONTH, 0);
50         lastday = format.format(cale.getTime());
51         System.out.println("本月第一天和最后一天分别是 : " + firstday + " and " + lastday);
52 
53         // 获取当前日期字符串
54         Date d = new Date();
55         System.out.println("当前日期字符串1:" + format.format(d));
56         System.out.println("当前日期字符串2:" + year + "/" + month + "/" + day + " "
57                 + hour + ":" + minute + ":" + second);
58     }
59 }

二、字符串转日期

/**
 * 字符串转换成日期
 *
 * @作者:张帅
 * @日期:2019-04-22
 * @param str
 * @return date
 */
public static Date strToDate(String str) {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //ZCLG20170630 添加日期格式 mod LiGe 20170630
    if(str.indexOf('年') > -1 && str.indexOf('月') > -1 && str.indexOf('日') > -1){
        format = new SimpleDateFormat("yyyy年MM月dd日");
    }else if(str.indexOf('年') > -1 && str.indexOf('月') > -1 && str.indexOf('号') > -1){
        format = new SimpleDateFormat("yyyy年MM月dd号");
    }
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

三、获取时间的年月日

1、jdk7

String year1=String.format("%tY", startDate);
String year2=String.format("%tY", endDate);
String mon1=String .format("%tm", startDate);
String mon2=String .format("%tm", endDate);
String day1=String .format("%td", startDate);
String day2=String .format("%td", endDate);

四、jdk8关于时间的新函数及其使用

4.1、LocalDateTime 

 1 import java.time.LocalDateTime;
 2 import java.time.format.DateTimeFormatter;
 3 import java.time.temporal.ChronoUnit;
 4 
 5 public class Test2 {
 6     public static void main(String[] args) {
 7         DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 8         LocalDateTime localDateTime = LocalDateTime.now().minus(1, ChronoUnit.MONTHS);
 9         System.out.println(localDateTime.format(dateTimeFormatter));
10     }
11 }

4.2、ChronoUnit

4.3、Duration

五、时间戳

1、方式一

//得到执行时间
/*String times="2018-03-31";
Date date=null;
try {
    date= TimeUtils.getDate(times,"yyyy-MM-dd");
} catch (ParseException e) {
    e.printStackTrace();
}
long t0 = System.currentTimeMillis(); // 代码执行前时间
BigDecimal exch=null;
for(int i=0;i<=400;i++){
    exch=dataDictionaryService.getExch("CNY","CNY",date);
}

long t1 = System.currentTimeMillis(); // 代码执行后时间
Calendar c = Calendar.getInstance();
c.setTimeInMillis(t1 - t0);
System.out.println("耗时: " + c.get(Calendar.MINUTE) + "分 "
        + c.get(Calendar.SECOND) + "秒 " + c.get(Calendar.MILLISECOND)
        + " 微秒");

2、方式二

package com.asd.common.utils.datetag;
import java.util.Date;
public class DateTag {
   private Date startDate;
   private Date lastDate;
   private StringBuilder info =  new StringBuilder();
   private int messageIndex = 0;

   public DateTag(String message) {
      this.lastDate = new Date();
      this.startDate = new Date();
      info.append(message);
      info.append(":");
      this.messageIndex = message.length()+1;
   }
   public void appendDate(String message){
      info.append(message);
      info.append(":");
      info.append(new Date().getTime()-lastDate.getTime());
      info.append(";");
      this.lastDate = new Date();
   }
   public void addFist(String message){
      info.insert(messageIndex, ";");
      info.insert(messageIndex, new Date().getTime()-startDate.getTime());
      info.insert(messageIndex, ":");
      info.insert(messageIndex, message);
      this.lastDate = new Date();
   }
   public String getInfo(){
      return info.toString();
   }
}
DateTag tag = new DateTag("sss");
BigDecimal ss = exch == null ? BigDecimal.ZERO : exch.getExchRate().divide(new BigDecimal(exch.getBase()));
tag.appendDate("从数据字段获取用时");
tag.addFist("总用时");
System.out.println(tag.getInfo());

 3、方式三

1 StopWatch sw = new StopWatch("导出合约检查单");
2 sw.start("获取基础数据");
3 TreatyCheckListSheets sheets = prepareBaseData(treatyIds);
4 sw.stop();
5 sw.start("导出数据");
6 exportCheckList(sheets,response);
7 sw.stop();
8 System.out.println(sw.prettyPrint());

 

posted @ 2021-09-12 13:39  慎终若始  阅读(92)  评论(0编辑  收藏  举报