1

我正在使用此代码获取上一个日期,但我想获取不包括日期的日期Saturday and Sunday

我用来获取上一个日期的代码:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static String previousDateString(String dateString) 
            throws ParseException {
        // Create a date formatter using your format string
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // Parse the given date string into a Date object.
        // Note: This can throw a ParseException.
        Date myDate = dateFormat.parse(dateString);

        // Use the Calendar class to subtract one day
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(myDate);
        calendar.add(Calendar.DAY_OF_YEAR, -1);

        // Use the date formatter to produce a formatted date string
        Date previousDate = calendar.getTime();
        String result = dateFormat.format(previousDate);

        return result;
    }

    public static void main(String[] args) {
        String dateString = "2012-08-20";

        try {
            // This will print 2012-08-19
            System.out.println(previousDateString(dateString));
        } catch (ParseException e) {
            System.out.println("Invalid date string");
            e.printStackTrace();
        }
    }
}`

它工作正常,但需要获取不是周六或周日的前一个日期。

问候

4

1 回答 1

2

您应该从对象中获取 ,如果它的日期是减去天数,或者如果然后从日期/日历对象中减去天数。DAY_OF_WEEKcalendarnextMONDAYthreeSUNDAYtwo

 calendar.setTime(myDate);
 int dayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
 if(dayOfWeek==Calendar.MONDAY)
    calendar.add(Calendar.DAY_OF_YEAR, -3); 
 else
 if(dayOfWeek==Calendar.SUNDAY)
    calendar.add(Calendar.DAY_OF_YEAR, -2);
 else
    calendar.add(Calendar.DAY_OF_YEAR, -1);
于 2012-08-20T07:11:33.727 回答