首页 > 代码库 > Calendar 得到前一天当前时间

Calendar 得到前一天当前时间

@Test    public void test(){            //因为Calendar的构造方法是私有的,所以实例化一个Calendar对象用getInstance方法        Calendar calendar = Calendar.getInstance();                calendar.add(Calendar.DATE, -1);    //得到前一天                Date date = calendar.getTime();                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            System.out.println(df.format(date));            }

这是一个非常好的实例,易于理解,能够帮助我们轻松掌握Calendar的使用方法。可以看点源码,底层使用Map集合实现的

public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {        if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {            return null;        }        // ALL_STYLES        if (style == ALL_STYLES) {            Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale);            if (field == ERA || field == AM_PM) {                return shortNames;            }            Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale);            if (shortNames == null) {                return longNames;            }            if (longNames != null) {                shortNames.putAll(longNames);            }            return shortNames;        }        // SHORT or LONG        return getDisplayNamesImpl(field, style, locale);    }    private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);        String[] strings = getFieldStrings(field, style, symbols);        if (strings != null) {            Map<String,Integer> names = new HashMap<String,Integer>();            for (int i = 0; i < strings.length; i++) {                if (strings[i].length() == 0) {                    continue;                }                names.put(strings[i], i);            }            return names;        }        return null;    }

 

Calendar 得到前一天当前时间