If I have a specific date of a day, how do I get the date of that day in the previous week?

后端 未结 4 1734
长发绾君心
长发绾君心 2021-02-19 18:15

SEE ANSWER FROM @Basil Bourque for most up to date answer


For example, if I have a \"Date\" variable \"date1\" with a value of (dd/mm/yyy) 03/07/2011, which is a S

4条回答
  •  悲&欢浪女
    2021-02-19 18:48

    You should use Calendar:

        Calendar date = new GregorianCalendar(2011, Calendar.JULY, 3);
        date.add(Calendar.DAY_OF_MONTH, -7);
        System.out.println(date.getTime());
    

    You can create a calendar from date too:

        Date date1 = new Date(111, Calendar.JULY, 3);//the year field adds 1900 on to it.
        Calendar date = new GregorianCalendar();
        date.setTime(date1);
        date.add(Calendar.DAY_OF_MONTH, -7);
        date2 = date.getTime();
    

    Be aware that:

    • Java uses 0 to represent January !
    • Date(year, month, day) is deprecated since JDK version 1.1 !

    See the GregorianCalendar JavaDoc:

    Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. Parameters: year the value used to set the YEAR calendar field in the calendar. month the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January. dayOfMonth the value used to set the DAY_OF_MONTH calendar field in the calendar.

提交回复
热议问题