2

How to get the date from the date format

dd/MM/yyyy

Example:

04/05/2015

I only need the date as 04.

Here is code snippet:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date(); 
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH,1);
System.out.println(dateFormat.format(date));

How to solve this issue?

catch23
  • 17,519
  • 42
  • 144
  • 217
Shiva Ravi
  • 17
  • 3

3 Answers3

2

Use cal.get(Calendar.DAY_OF_MONTH).

Aakash
  • 2,029
  • 14
  • 22
2

Simply change DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); to DateFormat dateFormat = new SimpleDateFormat("dd"); or use cal.get(Calendar.DAY_OF_MONTH);

Jens
  • 67,715
  • 15
  • 98
  • 113
2

You need to change pattern which shows to you desired data format:

DateFormat dateFormat = new SimpleDateFormat("dd");

instead of

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

UPDATE:

Java 1.8 has updated data and time API.

Here is snippet of code which I checked:

    LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
    System.out.println("last april day: " + lastAprilDay);
    LocalDate firstMay = lastAprilDay.plusDays(1);
    System.out.println("should be first may day: " + firstMay);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
    String formatDate = formatter.format(firstMay);
    System.out.println("formatted date: " + formatDate);

Output:

last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01

For more info see Java documentations to this classes:

catch23
  • 17,519
  • 42
  • 144
  • 217