簡體   English   中英

如何從 java 中的給定日期獲取前 12 個月的日期

[英]How to get 12 months previous date from given Date in java

如何從 java 中的給定日期獲取前 12 個月的日期

例如:輸入 - 2019 年 11 月 12 日 output -12/2018 年 11 月

問題

這不是一個不常見的問題,之前已經被問過並回答了很多次。

問題是,我至少可以想到 4 種方法,但只有一種方法(截至今天)被推薦。

1.手動操作

這是您將String值分解為單獨的部分並簡單地從它們中減去值的時候。

這絕不是一個好主意,可能是你能做的最糟糕的事情。 手動時間操作(即使在毫秒級別)絕不是您應該尋找的解決方案 - 有很多圍繞日期/時間的規則。

2. 使用Calendar

Java 1.1 引入了Calendar class,在沒有更好的情況下,我們忍受了它。 如果你沒有別的東西,你還是應該避免它

您可以做一些觀察,看看為什么不再推薦它,例如Java 的舊日期和日歷 API 不好的 5 個原因

3.喬達時間

在 Java 8 引入新的日期/時間 API 之前,這將是日期/時間操作的推薦庫。

If you're still using a version of Java below 8, then you should consider using ThreeTen Backport library instead, which takes the date/Time API from Java 8 and makes it available for earlier versions of Java. 我相信還有一個 Android 的版本。

4. Java 8+ 日期/時間 API

Java 8 引入了新的日期/時間 API ,這是目前 Java 中推薦的操作日期/時間值的方法。

在幾乎所有情況下,不推薦使用其他所有方法,您應該避免使用它們(如果不能,請使用 ThreeTen 反向移植!)

因此,以最簡單的形式,您可以使用類似...

LocalDate startDate = LocalDate.of(2019, Month.NOVEMBER, 12);
LocalDate endDate = startDate.minusYears(1);

System.out.println(startDate);
System.out.println(endDate);

哪個會打印

2019-11-12
2018-11-12

但是等等,我的輸入是一個String

然后您將需要使用DateTimeFormatter ,配置為匹配您的輸入,然后將其解析為LocalDate值。

但是再一次,一點點的凝視將展示大量的可能性和例子

但我希望輸出格式為 [在此處插入您想要的 output 格式]

然后你需要使用DateTimeFormatter ,配置為匹配你想要的 output 然后格式化LocalDate

再一次,一點點凝視將展示大量的可能性和例子

您可以使用此方法從任何日期減去月數

public static String subtractMonthsFromDate(String date, int month, String dateFormat) {
    final SimpleDateFormat format = new SimpleDateFormat(dateFormat);
    Calendar calendar=Calendar.getInstance();
    try {
        calendar.setTime(format.parse(date));
        calendar.add(Calendar.MONTH, -month);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return format.format(calendar.getTime());
}

您可以使用日歷 object 實例:-

private static String getPrevious12MonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.MONTH, -12);  

    Date pre12MonthDate = cal.getTime();  
    return format.format(preMonthDate);
}

最佳解決方案取決於您如何表示日期。 我創建了兩個函數來完成你的任務。 一個接受格式上的字符串輸入(“dd/MM/YYYY”),而另一個使用 DateTimeFormatter 類將 LocalDate 對象轉換為字符串。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class Main{

  public static void main(String args[]){

    System.out.println(subtractYear("10/10/2019")); // Prints 10/10/2018
    System.out.println(subtractYear("10/10/1999")); // Prints 10/10/1998
    System.out.println(subtractYear("10/10/10")); // Prints 10/10/9
    System.out.println(subtractYear(LocalDate.now())); // Prints 22/11/2018
  }

  /**
  * @param date Assumed to be in shape of dd/mm/yyyy
  */
  public static String subtractYear(String date){
    int year = 0;
    try {
      year = Integer.parseInt(date.substring(6));
    } catch (Exception e){
      // Invalid param
      return null;
    }
    String prevYear = date.substring(0,6) + (year - 1);
    return prevYear;
  }


  public static String subtractYear(LocalDate date){
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/YYYY");
    return subtractYear(dtf.format(date));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM