Search code examples
androiddatetimetimestampsimpledateformat

Android convert int timestamp to human datetime


Hi I have an android app using webRequestreturn timestamp of type Int (or Long) I want to convert it to human reader date time (according to devices timezone)

for example 1175714200 convert to GMT: Wed, 04 Apr 2007 19:16:40 GMT Your time zone: 4/5/2007, 3:16:40 AM GMT+8:00

I have use this function to convert but seem not return correct result (all result is like (15/01/1970 04:04:25) which is not correct

time.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
                format(new Date(topStory.getTime() * 1000)));

Anything wrong with the above code?

I also have the warning message:

To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates. less... (Ctrl+F1) Almost all callers should use getDateInstance(), getDateTimeInstance(), or getTimeInstance() to get a ready-made instance of SimpleDateFormat suitable for the user's locale. The main reason you'd create an instance this class directly is because you need to format/parse a specific machine-readable format, in which case you almost certainly want to explicitly ask for US to ensure that you get ASCII digits (rather than, say, Arabic digits).


Solution

  • Try this function:

    private String formatDate(long milliseconds) /* This is your topStory.getTime()*1000 */ {
        DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        TimeZone tz = TimeZone.getDefault();
        sdf.setTimeZone(tz);
        return sdf.format(calendar.getTime());
    }
    

    It gets the default timezone from the device it's being used on. If you have any questions/doubts, please comment. Also, this function takes as input the number of milliseconds since the last epoch. If that's not what your topStory.getTime() is returning, this function will not work. In that case, you would need to convert the return value of topStory.getTime() to the number of milliseconds since the last epoch.