Get first date of current month in java

前端 未结 9 1787
日久生厌
日久生厌 2020-11-29 05:28

I am trying to get to and from date where ToDate will have previous date and FromDate will have first date of the current month. For January it wou

9条回答
  •  情话喂你
    2020-11-29 06:15

    If you also want the time is set to 0 the code is:

    import java.util.*;
    import java.text.*;
    
    public class DateCalculations {
      public static void main(String[] args) {
    
        Calendar aCalendar = Calendar.getInstance();
    
        aCalendar.set(Calendar.DATE, 1);
        aCalendar.set(Calendar.HOUR_OF_DAY, 0);
        aCalendar.set(Calendar.MINUTE, 0);
        aCalendar.set(Calendar.SECOND, 0);
    
        Date firstDateOfCurrentMonth = aCalendar.getTime();
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    
        String dayFirst = sdf.format(firstDateOfCurrentMonth);
        System.out.println(dayFirst);
      }
    }
    

    You can check online easily without compiling by using: http://www.browxy.com/

提交回复
热议问题