-1

I really need your help. I have searched and tried every example I could use, but none have worked.

I need to store current date in YYYY-MM-DD format in a text file..the String date has to be a string..

String dateF = "YYYY-MM-DD";
Date dateOnly = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(dateF);
String date = dateFormat.format(dateOnly);

when I tried that code above.. this the output I got

please|work|2016-04-110|11

please help me...this is my assignment due this Friday ): I just need this date and 2 other things to be done.. thanks :)

Woodchuck
  • 3,869
  • 2
  • 39
  • 70
Preeyah
  • 363
  • 3
  • 16
  • 42

3 Answers3

3

your issue comes from the case you used for Y and D. according to the API SimpleDateFormat documentation, you should use d (day in month) instead of D (day in year), in your format definition.

    String dateF = "yyyy-MM-dd";    
Loic Mouchard
  • 1,121
  • 7
  • 22
1

Format being used is incorrect.

YYYY-MM-DD : Capital DD will return Day in the year. So, 11 April corresponds to 110th day in the year.

yyyy-MM-dd : Small dd will return the Day in the month.

Refer: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
0

Use this code :

Calendar c = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(c.getTime());

The formattedDate contain 2016-04-19

Edit :

In your code change the YYYY to yyyy and DD to dd.

Community
  • 1
  • 1