如何在不使用Java中的Calendar且没有日期的时间戳的情况下获得昨天的日期? [英] How can I get yesterday's date without using Calendar in Java and without a timestamp just the date?

查看:191
本文介绍了如何在不使用Java中的Calendar且没有日期的时间戳的情况下获得昨天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一种方法,以 yyyy-MM-dd 的格式获取当前日期,并希望能够创建另一种获取昨天日期的方法,当前日期的前一天。所有这些需要的只是日期,而不是时间戳。我也不想使用 Calendar 。我已经这样设置了当前日期:

I have wrote a method to get the current date in the format of yyyy-MM-dd and want to be able to also create another method for getting yesterday's date, the day before the current date. All this needs is the date and not the timestamp. I am not trying to use Calendar as well. I have set up the current date this way:

public class DateWithNoTimestamp
{
       private static final String CURRENT_DATE_FORMAT = "yyyy-MM-dd";

       public final static String getCurrentDate()
       {
               DateFormat dateFormat = new SimpleDateFormat(CURRENT_DATE_FORMAT);
               Date date = new Date();
               return dateFormat.format(date);
       } 
}

这可以获取当前日期,现在是单独的日期方法 getYesertdayDate()我遇到了麻烦。如何在减去一天的同时以与 getCurrentDate()相似的方式进行设置?

This works to get the current date, now the separate method getYesertdayDate() I'm having trouble with. How can I set it up in a similar way as I did with getCurrentDate() while subtracting one day ?

推荐答案

您可以简单地减去 1000 * 60 * 60 * 24 毫秒从该值的日期和格式开始:

You could simply subtract 1000 * 60 * 60 * 24 milliseconds from the date and format that value:

Date yesterday = new Date(System.currentTimeMillis() - 1000L * 60L * 60L * 24L));

这是一种肮脏的方式,而且正如评论中指出的那样,当发生夏令时转换(每年两天)。推荐的替代方法是日历API Joda API 或新的JDK 8时间API:

That's the quick-and-dirty way, and, as noted in the comments, it might break when daylight savings transitions happen (two days per year). Recommended alternatives are the Calendar API, the Joda API or the new JDK 8 time API:

LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);

这篇关于如何在不使用Java中的Calendar且没有日期的时间戳的情况下获得昨天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆