Get first date of current month in java

前端 未结 9 1745
日久生厌
日久生厌 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:07

    Works Like a charm!

    public static String  getCurrentMonthFirstDate(){
        Calendar c = Calendar.getInstance();   
        c.set(Calendar.DAY_OF_MONTH, 1);
        DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
        //System.out.println(df.format(c.getTime())); 
        return df.format(c.getTime());
    }
    

    //Correction :output =02-01-2018

    0 讨论(0)
  • 2020-11-29 06:08

    Joda Time

    If I am understanding the question correctly, it can be done very easily by using joda time

    LocalDate fromDate = new LocalDate().withDayOfMonth(1);
    LocalDate toDate = new LocalDate().minusDays(1);
    
    0 讨论(0)
  • 2020-11-29 06:12

    You can use withDayOfMonth(int dayOfMonth) method from java8 to return first day of month:

    LocalDate firstDay = LocalDate.now().withDayOfMonth(1);
    System.out.println(firstDay);   // 2019-09-01
    
    0 讨论(0)
  • 2020-11-29 06:12
    import java.util.Date;
    import java.text.SimpleDateFormat;
    
    ...
    Date currentMonth = new Date();
    String yyyyMM = new SimpleDateFormat("yyyyMM").format(currentMonth);
    Date firstDateOfMonth = new SimpleDateFormat("yyyyMM").parse(yyyyMM);
    ...
    

    my stupid solution. but it's work for me :D

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-29 06:18
    Calendar date = Calendar.getInstance();
    date.set(Calendar.DAY_OF_MONTH, 1);
    
    0 讨论(0)
提交回复
热议问题