java 如何获得昨天的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38955993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:56:24  来源:igfitidea点击:

how to get yesterday date

javaandroid

提问by Mariana

I want to get yesterday date or date which is of not today but of the past. I am using this code -

我想获得昨天的日期或不是今天而是过去的日期。我正在使用此代码 -

Calendar calendarMessage = Calendar.getInstance();
        Calendar calendarToday = Calendar.getInstance();
        calendarMessage.setTime(date);
        return calendarMessage.get(Calendar.YEAR) == calendarToday.get(Calendar.YEAR) &&
                calendarMessage.get(Calendar.DAY_OF_YEAR) == calendarToday.get(Calendar.DAY_OF_YEAR);

Can you please help me in this?

你能帮我吗?

回答by Hardik Parmar

Try on this way ..

试试这个方法..

public static String getYesterdayDate() {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    return dateFormat.format(cal.getTime());
}

回答by somelement

The following should work for you:

以下应该对你有用:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());

private String getYesterdayDateString() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);    
        return dateFormat.format(cal.getTime());
}