有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在某一天之前到达

我想为某个特定的日期缩短一天。但在一个月内会减少

df = new SimpleDateFormat("EEEE, dd MMMM YYYY"); 
Date prevDate = df.parse(dateText.getText().toString()); 
Calendar c = Calendar.getInstance(); 
c.setTime(prevDate); 
c.add(Calendar.DATE, -1); 
Date d=c.getTime(); 
dateText.setText(df.format(d));

共 (2) 个答案

  1. # 1 楼答案

    java.time.LocalDate

    您可以使用^{}如下所示

            String dateText="Mon, 14 May 2018";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMMM yyyy", Locale.ENGLISH);
            LocalDate localDate = LocalDate.parse(dateText, formatter);
            localDate = localDate.minusDays(1);
    

    最好避免Date类。但如果必须的话,你可以皈依

    Date oneDayBefore = 
        Date.from(                       // New conversion method added to the old class.
            localDate
            .atStartOfDay(               // Determine the first moment of the day as seen in that time zone. Not always 00:00.
                ZoneId.systemDefault()
            )                            // Returns another `LocalDate` object.
            .toInstant()                 // Returns a `Instant`.
        )
    ;                                    // Only if you *really* need java.util.Date object.
    

    打印结果

            System.out.println(oneDayBefore);
            String dateTextOneDayBefore = formatter.format(localDate);//Format to similar to input 'dateText'
            System.out.println(dateTextOneDayBefore);
    
  2. # 2 楼答案

    如果坚持使用日历,请尝试以下操作:

    Calendar c = Calendar.getInstance(); 
    c.setTime(prevDate); 
    c.add(Calendar.HOUR, -24); 
    

    但你也会使用毫秒。 在这种情况下,也许以下几点就足够了:

    date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
    

    最好的方法是使用JodaTime:

    DateTimeFormat format = DateTimeFormat.forPattern("yyyy-MM-dd 00:00:00.000000000");
    DateTime now = new DateTime();
    System.out.println("Previous :" + format.print(now);
    DateTime oneDayAgo = now.minusDays(1);
    System.out.println("Updated :" + format.print(oneDayAgo);
    

    我会使用JodaTime,尤其是如果你的应用程序中有更多的日期/时间操作