-1

I have the following date which is the following type:Date java.util.Calendar.getTime()

Thu Jan 21 14:54:30 AST 2016

I want to remove time from the date part, in a normal way I would do it this way:

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
outputFormatter .format(mydate);

which works perfectly fine but I am curious to see if there is a better way doing it using Java Time API?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
HMdeveloper
  • 2,772
  • 9
  • 45
  • 74

1 Answers1

2

If you start from a Calendar, you can do:

Calendar c = Calendar.getInstance();
Instant instant = Instant.ofEpochMilli(c.getTimeInMillis());
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();

You can then format it with a DateTimeFormatter if you want.

Note however that the idea of the new API is to NOT use Calendar or Date at all, unless you get them from methods that you can't change.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • To be clear, `java.util.Date` & `java.util.Calendar` are the old date-time classes bundled with the earliest versions of Java. Avoid them. They have been supplanted by the [`java.time`](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes built into Java 8 and later, such as `java.time.Instant` and `java.time.LocalDate` classes seen here in this correct Answer. – Basil Bourque Jan 22 '16 at 00:55