0

How can I do this?

Year 2019, Month July, Date 30

Exact in this format and from Calendar (java.util) object Only


private String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat mdformat = new SimpleDateFormat("yyyy-MM-dd");
        return mdformat.format(calendar.getTime()); }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 2
    please precise your question. Do you want to get current date from Calendar or you want to substring a string and print date in order you gave? – Domin Jun 04 '19 at 15:50
  • @Domin check my answer – Pooja Singh Jun 04 '19 at 15:55
  • Is your code working as expected? If so, what was the question? If not, please be precise about desired and observed result. Quote any error message verbatim. It’s your best chance to get good help. – Ole V.V. Jun 04 '19 at 19:04
  • Possible duplicate of [What is the easiest way to get the current date in YYYYMMDD format?](https://stackoverflow.com/questions/31138533/what-is-the-easiest-way-to-get-the-current-date-in-yyyymmdd-format) and many other questions. Please search before posting your question and find a good answer faster. – Ole V.V. Jun 04 '19 at 19:30
  • Is that code snippet part of the question or is it your own answer to it? In the latter case it should have stayed an answer as you had first posted it, and we need a moderator to change it back into that. – Ole V.V. Jun 04 '19 at 19:47

2 Answers2

1

If you want to use only Calendar:

Calendar c = Calendar.getInstance();
String result = "Year " + c.get(Calendar.YEAR) +
                ", Month " + new SimpleDateFormat("MMMM").format(c.getTime()) +
                ", Date " + c.get(DAY_OF_MONTH);
System.out.println(result);

Will print:

Year 2019, Month June, Date 4

If you don't want to use even SimpleDateFormat:

String[] months = {
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
};
Calendar c = Calendar.getInstance();
String result = "Year " + c.get(Calendar.YEAR) +
        ", Month " + months[c.get(Calendar.MONTH)] +
        ", Date " + c.get(DAY_OF_MONTH);
System.out.println(result);

Will also print:

Year 2019, Month June, Date 4
forpas
  • 160,666
  • 10
  • 38
  • 76
0

Text can be included in the SDF string so using your code :

SimpleDateFormat mdFormat = new SimpleDateFormat("'Year 'yyyy', Month 'MMMM', Date 'dd");

The point of this answer is to indicate you can include text in your date format; SDF has some subtleties (e.g. LLLL may be better for language support) which are not addressed here.