0

I want to store date and time that user picks through date picker and time picker on Android. By reading various thread I came to conclusion to store date and time in INTEGER format. So I'm converting them to long values using following function but when I'm converting them back to Date it is giving me wrong Date.

private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener(){

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        String dateText = getTimeString(year,monthOfYear,dayOfMonth);
        //Converting Date to long so that can be stored in DB
        long date = Utility.getDateLong(year,monthOfYear,dayOfMonth);
        taskModel.setStartDate(date);
        startDateView.setText(dateText);
    }
};

 public static long getDateLong(int year, int month, int day){
    Calendar cal = new GregorianCalendar(year, month, day);
    long timeStamp = (cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000;
    return timeStamp;
}

To convert long value back to Date I'm using the below function :

public static String getDateFromLongValue(long d){
    Date date = new Date(d);
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String formattedDate = dateFormat.format(date);
    return formattedDate;
}

But this is giving me the different date then the entered value. Is there any other way to do this. I basically need to compare dates and to find the time elapsed between two dates?

Paras
  • 3,191
  • 6
  • 41
  • 77
  • I use TimeStrings ([see](https://www.sqlite.org/lang_datefunc.html)). Someone prefers integers. Choose your method. – Phantômaxx Jul 11 '16 at 16:39
  • Why not use Gregorian calendar while converting back again to make sure you are accounting for timezone offset ?? – Ramesh Jul 11 '16 at 16:48
  • I like using epoch time when storing dates in a DB. Then do conversion client-side/front-end – mastrgamr Jul 11 '16 at 16:51
  • Possible duplicate of [Sqlite convert string to date](http://stackoverflow.com/questions/4428795/sqlite-convert-string-to-date) – MPelletier Jul 11 '16 at 21:35

1 Answers1

1

I suggest a duplicate because while "best way" is theoretically debatable, SQLite offers date functions based on the fact that SQLite doesn't have a time and date type, but does offer date functions based ISO-formatted TEXT timestamp.

One item that is definitely not a matter of opinion though is where you want to do the bulk of operations. You have two choices:

  1. Query for a large amount of data then filter that in your app
  2. Query for a subset of that data

You might will run into timing and memory issues if you don't pre-filter your dataset via the query (i.e. using date and time functions off an ISO-formatted text timestamp) and opt to transform epochs in Java.

MPelletier
  • 16,256
  • 15
  • 86
  • 137