Search code examples
androiddateunix-timestamp

android timestamp parsing gone wrong(always in 1970)


im trying to convert a string(with unix timestamp) to an date with the format ( dd-MM-yyyy)

and this is working partly. The problem im having now is that my date is in 17-01-1970 (instead of march 16 2015)

im converting it like this:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date d = null;
    int dateMulti = Integer.parseInt(Date);
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(dateMulti);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();

    Log.d("test",date);
    try {
        d = dateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

where Date = 1427101853 and the result = 17-01-1970

what am i doing wrong?


Solution

  • You are using the wrong format string in the first line:

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
    

    mm is minutes. Use MM (months) instead.

    edit A Unix timestamp is a number of seconds since 01-01-1970 00:00:00 GMT. Java measures time in milliseconds since 01-01-1970 00:00:00 GMT. You need to multiply the Unix timestamp by 1000:

    cal.setTimeInMillis(dateMulti * 1000L);