-1

I know that this question that I am asking has answer all over the net but I want the yyyy-MM-dd format in Date type as SimpleDateFormat.format("yyyy-MM-dd") returns the string value and also I have tried SimpleDateFormat.parse("yyyy-MM-dd") but it does not provide the value in required format. Could anyone help how to get "yyyy-MM-dd" format in Date type variable. Example what I am trying to do is shown below-

Date date = new Date();     // this will give the outpur something like this Thu 28 Nov....

But I want the output in this format 2019-11-28 where date variable should not change its type.

  • Date is just an object holding a typed value. `You can only format its output not the date itself`. Which is where `SimpleDateFormat` comes in for formatting the output of a date. – Giddy Naya Nov 28 '19 at 09:34
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 28 '19 at 18:23
  • You are asking the impossible. A `Date` hasn’t got, as in cannot have a format. See the linked originals for details. – Ole V.V. Nov 28 '19 at 18:24
  • Allow me to suggest `LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));`. A `LocalDate` hasn’t got a format either, but its `toString` method produces a string in the format you are asking for, so you can at least pretend… – Ole V.V. Nov 28 '19 at 20:41

4 Answers4

2

tl;dr

Capture the current date, using java.time.LocalDate.

LocalDate                              // Represent a date-only value, without time-of-day and without time zone.
.now(                                  // Capture the current date. Time zone required, as the date is not the same around the globe.
    ZoneId.of( "Pacific/Auckland" )
)                                      // Returns a `LocalDate` object.
.toString()                            // Generates a `String` object whose text is in standard ISO 8601 format: YYYY-MM-DD

2020-01-23

Perhaps you are being handed a java.util.Date object by old code not yet updated to java.time classes. Convert from a given java.util.Date object (legacy) to Instant & ZonedDateTime (modern).

myJavaUtilDate                          // `java.util.Date` is one of the terrible date-time classes, now legacy. 
.toInstant()                            // Convert to the modern `java.time.Instant` class that replaces `Date`. 
.atZone(                                // Adjust from UTC to the time zone through which you want to perceive the date.
    ZoneId.of( "Asia/Tokyo" )           // Specify a proper time zone in `Continent/Region` format, never 2-4 letter pseudo-zone such as PDT, CST, IST, and such.
)                                       // Returns a `ZonedDateTime` object.
.format(                                // Generate text representing the value within our `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE    // Specify a formatter. Here, the standard ISO 8601 formatter for date-only value: YYYY-MM-DD. 
)                                       // Returns a `String`.

2020-01-23

java.time

You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.

LocalDate

If you just want the current date, use LocalDate.now.

LocaleDate.now( ZoneId.of( "Europe/Berlin" ) ).toString() // Yields something like '2020-01-23'.

Instant

Convert java.util.Date to its replacement, java.time.Instant. Both represent a moment in UTC, though the modern class has a fiber resolution of nanoseconds versus milliseconds.

To convert, use new to/from methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

ZonedDateTime

For any given moment, the date varies around the globe by time zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

So determining a date requires a time zone.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ; 
ZonedDateTime zdt = instant.atZone( z ) ;

Text

Could anyone help how to get "yyyy-MM-dd" format in Date type variable.

Text has a “format”, but date-time objects do not. Date-time objects can be instantiated by parsing text. Date-time objects can generate text to represent t the value held internally. But the date-time object and the String object are separate and distinct.

Generate text for the date only, without the time of day and without the time zone appearing.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE ) ; 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Try this one:

Date date = new Date();  
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");  
String strDate= formatter.format(date);  
System.out.println(strDate); 

or check this site: https://www.javatpoint.com/java-simpledateformat

OMS
  • 1
  • 5
  • I know the solution which you have provided but I dont want the date in string format. I want that my date should be in date type but the format should be changed. – Tanisha Agarwal Nov 28 '19 at 09:33
  • @TanishaAgarwal Date-time objects do not have a “format”. Only their textual representation has a format. – Basil Bourque Nov 28 '19 at 22:10
0

Convert it to java.sql.Date :

   Date obj = new Date();           
   java.sql.Date sqlDate = new java.sql.Date(obj.getTime());
   System.out.println(sqlDate);
Somil Garg
  • 474
  • 4
  • 12
  • 2
    While `java.util.Date` was poorly designed, `java.sql.Date` is a true hack in top of the already poorly designed `java.util.Date` class. Also the data types in `java.sql` were never intended for anything else than transferring data to and from SQL databases (for which we today prefer to use the types from java.time). I certainly don’t recommend using `java.sql.Date` here. – Ole V.V. Nov 28 '19 at 20:44
  • 2
    [`LocalDate.now()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#now(java.time.ZoneId)) is so much easier. – Basil Bourque Nov 28 '19 at 22:19
0

I don't think that you can change the format of a Date object itself, therefore you should use DateFormatters, like mentioned above the SimpleDateFormat.

Also, you maybe should consider using LocalDate/LocalDateTime or Instant instead of Date.

bbrinck
  • 953
  • 1
  • 9
  • 33