2016-12-14 77 views
2

美好的一天,我有时间戳1481709600,我想有这个时间格式Wed, 14 Dec 2016从时间戳日期的Android

我试图做到这一点使用:

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

但电流输出Sun Jan 18 05:35:09 GMT+02:00 1970

我认为日期格式不对,我需要使用哪一个?

谢谢!

更新

的问题是,今年的日期和月份是错误的,它应该是2016年12月14日,而不是1970年1月18日

回答

2

问题是你的时间戳为秒,这样你的时间戳转换成毫秒,然后使用日期格式功能。 ..

试试这个...

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);; 
    } 

输出: - 这样<code>Wed, 14 Dec 2016</code>

注: - EEE为代表的日一周中,MMM被代表为本月字等..

0

的日期格式是错误的;您必须使用

new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(date); 
+0

使用long而不是整数 – gauss

3

,你可以任意组合,如果你读this
您需要使用EEE, d MMM yyyy

更新

SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy"); 
sdf.format(new Date(1481709600)); 
0

试试这个方法来获取数据。放入setTimeInMillis时间长,而不是作为INT

private String getDate(long time) { 
    Calendar cal = Calendar.getInstance(Locale.ENGLISH); 
    cal.setTimeInMillis(time); 
    String date = DateFormat.format("EEE MMM dd hh:mm:ss yyyy ", cal).toString(); 
    return date; 
} 
+0

@VLeonovs 1481709600 * 1000然后它给你正确的日期。我已经提到你setTimeInMillis。 –

0

试试这个

private String getDateFromTimeStamp(long time) { 
     Calendar cal = Calendar.getInstance(Locale.ENGLISH); 
     cal.setTimeInMillis(time); 
     String date = DateFormat.format("EEE MMM dd hh:mm:ss yyyy ", cal).toString(); 
     return date; 
    } 
+0

@VLeonovs你传递的时间戳是什么。你所做的错误是,你已经使用'Integer'值作为参数,它应该是'long'数据类型,它是你在1970年作为年份的地方,尝试上面的代码并且如果你得到相同的输出 – SaravInfern

0

您可以创建一个简单的方法来获得如下从时间戳日期

public String getDateCurrentTimeZone(long timestamp) { 
     try { 
      Calendar calendar = Calendar.getInstance(); 
      TimeZone tz = TimeZone.getDefault(); calendar.setTimeInMillis(timestamp * 1000); 
calendar.add(Calendar.MILLISECOND, 
tz.getOffset(calendar.getTimeInMillis())); 
      SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); 
Date currenTimeZone = (Date) calendar.getTime(); 
return sdf.format(currenTimeZone); 
} catch (Exception e) { 
} 
return ""; 
} 
0

这个工作对我来说:

val currentDay = Date() 
    val day = currentDay.time 
    Logger.i("currentDay = $currentDay and day : $day ") 

    val c = Calendar.getInstance() 
    c.timeInMillis = day 
    val d = c.time 
    val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm") 

    Logger.i("meDate : ${sdf.format(d)}")