Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From timestamp to Date Android

Good day, I have timestamp 1481709600 and I would like to have this time format Wed, 14 Dec 2016

I'm trying to do that using:

private String getDateFromTimeStamp(Integer dt) {
            Date date = new Date (dt);
            return new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy ").format(date);
}

but the current output is Sun Jan 18 05:35:09 GMT+02:00 1970

I think the date format is wrong, which one I need to use ?

Thank you!

Update

the problem is that the year day and month is wrong, It should be 14 Dec 2016 instead of Jan 18 1970

like image 651
VLeonovs Avatar asked Dec 19 '22 11:12

VLeonovs


1 Answers

Problem is your timeStamp is in seconds , so convert your timeStamp into millisec and then use the date format function ...

try this one ...

JAVA

 private String getDate(long time) {
        Date date = new Date(time*1000L); // *1000 is to convert seconds to milliseconds
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy "); // the format of your date
        sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
    
        return sdf.format(date);;
    }

Kotlin

fun getDate(time:Long):String {
            var date:Date = Date(time*1000L); // *1000 is to convert seconds to milliseconds
            var sdf:SimpleDateFormat  = SimpleDateFormat("EEE, dd MMM yyyy "); // the format of your date
            sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
    
        return sdf.format(date);
    }

Output:- like this Wed, 14 Dec 2016

Note:- EEE is represent as Day in Week ,MMM is represent as Month in words and so on ..

like image 186
sushildlh Avatar answered Jan 09 '23 10:01

sushildlh