0

I am trying the code

    Date today = new Date();
    Date todayWithZeroTime;
    {
        try {
            todayWithZeroTime = formatter.parse(formatter.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    String date = todayWithZeroTime.toString();

it is giving output :- Wed Dec 11 00:00:00 IST 2019 where I want 11/12/2019 where 11/12/2019 is today's date

AElMehdi
  • 572
  • 4
  • 12
  • You need to use an appropriate formatter to convert it to string... The `formatter.parse(formatter.format(today))` step isn't even necessary. But you should really switch to the modern `java.time` classes where this can be done a lot simpler and elegant. – Mark Rotteveel Dec 11 '19 at 12:07
  • `LocalDate.now()` –  Dec 11 '19 at 12:08
  • 1
    Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – Ajith Dec 11 '19 at 12:11
  • I recommend you don’t use `DateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 11 '19 at 13:03

2 Answers2

6

Using java.time.LocalDate,

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16

Use DateTimeFormatter to format the date as you want.

In your case the pattern is "dd/MM/yyyy".

Info ⬇️

Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar. The core classes of the new Java 8 project that are part of the java.time package like LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and their supported APIs.

The LocalDate provides various utility methods to obtain a variety of information. For example:

1) The following code snippet gets the current local date and adds one day:

LocalDate tomorrow = LocalDate.now().plusDays(1);

2) This example obtains the current date and subtracts one month. Note how it accepts an enum as the time unit:

LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);
Liuk
  • 351
  • 1
  • 13
  • 1
    Nice answer, to even improve it, place a hint to the Java version that introduced `java.time`... – deHaar Dec 11 '19 at 12:11
2

If you are using JAVA 8 you can use LocalDateTime class and DateTimeFormatter.

see below example using JAVA 8:

LocalDateTime now = LocalDateTime.now();
System.out.println("Current DateTime Before Formatting: " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatedDateTime = now.format(formatter);
System.out.println("Current DateTime after Formatting:: " + formatedDateTime );
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91