-2

Want to get the first day of month from current date.

To get that I'm doing with org.apache.commons.lang3.time.DateUtils to return in below format

DateUtils.truncate(new Date(), 2);

this is returning expected output like below:

Fri Jul 01 00:00:00 IST 2022

Is any other way to get the 1st day of the current month with the same above date time format?

Remo
  • 534
  • 7
  • 26
  • 6
    You should stop using `Date`, for it's obsolete. Use classes from the `java.time` package. In your case probably `ZonedDateTime`. – MC Emperor Jul 11 '22 at 07:31
  • 4
    Or possibly `LocalDate`, depending on how you want to handle time zones... (The requirements are really unclear at the moment.) – Jon Skeet Jul 11 '22 at 07:34
  • 4
    "...with the same above date time format" - Note that formats are a matter of string representation, i.e. they depend on a couple of things like timezone, locale etc. A date object (ideally one of the java.time versions) never has a _format_, it just represents a point in time. – Thomas Jul 11 '22 at 07:36
  • `String output = YearMonth.now(ZONE).atDay(1).atStartOfDay(ZONE).format(DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz y", Locale.ROOT))`. Set `ZONE` to your desired time zone. When I set it to `ZoneId.of("Asia/Kolkata")`, I got `Fri Jul 01 00:00:00 IST 2022`. – Ole V.V. Jul 11 '22 at 08:30

3 Answers3

5

You can use java.time.LocalDate.

LocalDate myLocalDate = LocalDate.now();
myLocalDate.withDayOfMonth(1));

Alternatively, use YearMonth.

YearMonth myYearMonth = YearMonth.now() ;
LocalDate myLocalDate = myYearMonth.atDay( 1 ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
sm3sher
  • 2,764
  • 1
  • 11
  • 23
1

If you are in jdk8, you can use java.time.LocalDate.

LocalDate now = LocalDate.now();
LocalDate res = now.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(res);

If the result type you want is Date.

ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
Timmy533
  • 9
  • 2
0

If you still want to use older Date library then :

        Calendar calendar =Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        System.out.println(calendar.getTime());

Output:(time zone varies based on your locale)

Fri Jul 01 08:54:39 BST 2022
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36