-4

I want to get a present time.The Date type of 'YY-MM-DD'.What should I do?

  • 3
    Please clarify your problem space and show pertinent code, both to help us understand you question. – Hovercraft Full Of Eels May 27 '17 at 05:17
  • I know the desired format in that other question is not the same, but the way to do is the same, so I trust you to tailor the answers from the other question to the format you are asking for. – Ole V.V. May 27 '17 at 07:16

2 Answers2

5

Assuming you are using Java 8+, use a DateTimeFormatter

String text = LocalDate.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));

In earlier versions, use a SimpleDateFormat like

String text = new SimpleDateFormat("yy-MM-dd").format(new Date());

While you can use the later in more recent versions, the former is generally preferred because date and time handling has been greatly improved by the java.time classes.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can do it by the below code.

public void getCurrentTimeStampInYYMMDDFormat() {
    String date = new SimpleDateFormat("yy-MM-dd").format(new Date());
}

If you are using JDK8 then, you can also do it like this:

public void getCurrentTimeStampInYYMMDDFormat() {
    String date = LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yy-MM-dd"));
}
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • 1
    Obviously ... he needs to modify the pattern if he wants to display the date as YY-MM-DD. The details are **in the javadocs**. – Stephen C May 27 '17 at 05:21
  • 1
    But the return type I need is Date. – blueblueblue May 27 '17 at 05:40
  • @blueblueblue please check now. – Avijit Karmakar May 27 '17 at 05:42
  • 1
    @blueblueblue Edit your Question to make clear your requirements. – Basil Bourque May 27 '17 at 06:49
  • 1
    Ah, one more of those. @blueblueblue, a `Date` cannot have a specific format in it, it’s just a point in time. How you format it lies outside the `Date` object. – Ole V.V. May 27 '17 at 07:06
  • See for example the discussions under [this question: How to initialize Gregorian calendar with date as YYYY-MM-DD format?](https://stackoverflow.com/questions/44180575/how-to-initialize-gregorian-calendar-with-date-as-yyyy-mm-dd-format) That is about `GregorianCalendar`, but no matter if we are talking `Date` or `GregorianCalendar` or `int`, the truth is the same: the variable does not (cannot) hold a string presentation in it. – Ole V.V. May 27 '17 at 07:12