CaptKirk
CaptKirk

Reputation: 63

Android SimpleDateFormat for a two digit month

I have a database in my Android app that has dates formatted like this: 201274 for July 4, 2012 and 20121016 for October 16, 2012. I display the date of the DB row using SimpleDateFormat so that for today, it grabs the date 20121016 and displays 2012-10-16. The code is like so:

    private void convertDBdate() {
    convertDateTextView.setText(gotDt);

    String dateStr = convertDateTextView.getText().toString();
    SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyyMd");
    SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");

    try { 
        DBdate = inputFormatter.parse(dateStr); 
        dashDateStr = outputFormatter.format(DBdate); 

        convertFinalDateTV.setText(dashDateStr); 
    } catch (ParseException e ) { 
        e.printStackTrace(); 
    }

With this code, 201274 displays fine as 2012-07-04, but two digit months display incorrectly, 20121016 shows as 2012-01-16 (January 16). The problem is in the MM and dd. I've tried yyyy-M-dd as the output date format, but that shows 2012-1-16 (again, January 16).

Do I have to somehow isolate the M value and do that month + 1 thing? If so how would that be written, and where would it go?

I don't want to have to re-write the dates in the database to 20120704 for July 4, 2012, I'd like to be able to fix it in code.

Upvotes: 0

Views: 1660

Answers (2)

dorjeduck
dorjeduck

Reputation: 7794

maybe to late for this project but for future projects I would always recommend to use

Date.getTime()

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getTime()

for storing even dates as it will take less space in the database, will make sorting faster and you just avoid problems you have right now.

Upvotes: 0

Paul D'Ambra
Paul D'Ambra

Reputation: 7814

Your problem isn't that the input formatter should always be yyyyMMdd but that sometimes it should be yyyyMMdd

in the case of 201274 then an input format of MM won't apply but in the case of 20121016 then it will.

You'll need to add some logic parsing the length of the input and choosing the appropriate formatter.

Before I could suggest some logic I'd need to ask two questions

  1. How do you represent 2012-10-01 in the database? I guess that it's 2012101 in which case...
  2. How do you distinguish between 2012111 and 2012111? i.e. 2012-11-01 and 2012-01-11

Upvotes: 1

Related Questions