服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - 使用java的Calendar对象获得当前日期

使用java的Calendar对象获得当前日期

2019-12-25 13:26hebedich JAVA教程

本文给大家分享的是使用使用java的Calendar对象获得当前日期的上几个度开始、结束时间,主要思路是先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期,十分的实用,小伙伴们可以参

思路:

先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
   * @param flag true:开始日期;false:结束日期
   * @return
   */
  public static String getLastQuarterTime(boolean flag){
    SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     
    String resultDate="";
    Date now = null;
    try {
      Calendar calendar = Calendar.getInstance();
      int currentMonth = calendar.get(Calendar.MONTH) + 1;
      //true:开始日期;false:结束日期
      if(flag){
        if (currentMonth >= 1 && currentMonth <= 3)
          calendar.set(Calendar.MONTH, 0);
        else if (currentMonth >= 4 && currentMonth <= 6)
          calendar.set(Calendar.MONTH, 3);
        else if (currentMonth >= 7 && currentMonth <= 9)
          calendar.set(Calendar.MONTH, 6);
        else if (currentMonth >= 10 && currentMonth <= 12)
          calendar.set(Calendar.MONTH, 9);
        calendar.set(Calendar.DATE, 1);
         
        now = longSdf.parse(shortSdf.format(calendar.getTime()) + " 00:00:00");
      }else{
        if (currentMonth >= 1 && currentMonth <= 3) {
          calendar.set(Calendar.MONTH, 2);
          calendar.set(Calendar.DATE, 31);
        } else if (currentMonth >= 4 && currentMonth <= 6) {
          calendar.set(Calendar.MONTH, 5);
          calendar.set(Calendar.DATE, 30);
        } else if (currentMonth >= 7 && currentMonth <= 9) {
          calendar.set(Calendar.MONTH, 8);
          calendar.set(Calendar.DATE, 30);
        } else if (currentMonth >= 10 && currentMonth <= 12) {
          calendar.set(Calendar.MONTH, 11);
          calendar.set(Calendar.DATE, 31);
        }
        now = longSdf.parse(shortSdf.format(calendar.getTime()) + " 23:59:59");
      }
      calendar.setTime(now);// 设置日期
      calendar.add(Calendar.MONTH, -3);
      resultDate = longSdf.format(calendar.getTime());
       
    } catch (Exception e) {
      ;
    }
    return resultDate;
  }

延伸 · 阅读

精彩推荐