0

I am fairly new to java and I am creating a fitness application.

Context: Database should add a new date entry every day the app is opened

Problem: Opened the app yesterday and it successfully added the date: 31.1.21. However opened it today and database has added 32.2.21 when it should be 1.2.21. Logs indicate that it must be an error with the code...

String timeStamp = new SimpleDateFormat("YYYY-MM-DD").format(Calendar.getInstance().getTime());
    timeStamp = timeStamp + " 00:00:00.000";
    android.util.Log.d(TAG, "Date/Time: " + timeStamp);

The code above is what is causing this issue, I am not familiar with Calendar and kindly ask if anyone knows what the issue could be. Many thanks.

  • Why you are adding this: ` " 00:00:00.000"` `String timeStamp = new SimpleDateFormat("YYYY-MM-DD").format(Calendar.getInstance().getTime());` This line is enough – Soumik Bhattacharjee Feb 01 '21 at 09:55
  • Hi Soumik, I have added " 00:00:00.000" to the current date because I want the database to acknowledge a new entry to be added at the start of each day. This is simply hard coded. Since it is a string concatenated to the end of the date it should not have any effect on the outcome? – Jungle Is Massive Feb 01 '21 at 10:03
  • Yes, that shouldn't affect, but as your code seems perfect to me, I was concerned about that line. Can you please log this line: `new SimpleDateFormat("YYYY-MM-DD").format(Calendar.getInstance().getTime());` and see if it works or not. – Soumik Bhattacharjee Feb 01 '21 at 10:14
  • Just logged without the added string: D/StepCounter: Date/Time: 2021-02-32 – Jungle Is Massive Feb 01 '21 at 10:17
  • 1
    Found solution: "YYYY-MM-DD" should be "yyyy-MM-dd" – Jungle Is Massive Feb 01 '21 at 10:35
  • Yeah, I just saw.. Learned something new.. I had no idea about the difference between dd & DD.. – Soumik Bhattacharjee Feb 01 '21 at 10:38

2 Answers2

1

Found solution:

"YYYY-MM-DD" should be "yyyy-MM-dd"

0

Ok, I got what went wrong there:

In DateFormat DD means Days in the year.. Whereas dd means Days in a month

So, the format should be this: "yyyy-MM-dd" instead of "YYYY-MM-DD"