How to get today's Date?

后端 未结 8 1932
予麋鹿
予麋鹿 2021-01-31 14:28

In other words, I want functionality that provides Joda-Time:

today = today.withTime(0, 0, 0, 0);

but without Joda-Time, only with java.util.Da

8条回答
  •  借酒劲吻你
    2021-01-31 15:00

    Code To Get Today's date in any specific Format

    You can define the desired format in SimpleDateFormat instance to get the date in that specific formate

     DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            String todaysdate = dateFormat.format(date);
             System.out.println("Today's date : " + todaysdate);
    

    Follow below links to see the valid date format combination.

    https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.

    For Example :

    Today date : 11/27/2018

    xdayFromTodaysDate = 2 to get date as 11/29/2018

    xdayFromTodaysDate = -2 to get date as 11/25/2018

      public String getAniversaryDate(int xdayFromTodaysDate ){
    
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
            date = cal.getTime();
            String aniversaryDate = dateFormat.format(date);
            LOGGER.info("Today's date : " + todaysdate);
              return aniversaryDate;
    
        }
    

    CODE : To get x days ahead or Previous from a Given date

      public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
    
    
            Calendar cal = Calendar.getInstance();
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            try {
                Date date = dateFormat.parse(givendate);
                cal.setTime(date);
                cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
                date = cal.getTime();
                String aniversaryDate = dateFormat.format(date);
                LOGGER.info("aniversaryDate : " + aniversaryDate);
                return aniversaryDate;
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
    
        }
    

提交回复
热议问题