字符串日期的时间戳

时间:2012-11-05 22:11:16

标签: android date timestamp

我不知道如何将时间戳转换为日期。 我有:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView czas = (TextView)findViewById(R.id.textView1);
    String S = "1350574775";
    czas.setText(getDate(S));        
}



private String getDate(String timeStampStr){
   try{
       DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
       Date netDate = (new Date(Long.parseLong(timeStampStr)));
       return sdf.format(netDate);
   } catch (Exception ignored) {
    return "xx";
   }
} 

答案是:1970年1月16日,但这是错误的。

3 个答案:

答案 0 :(得分:58)

如果您坚持使用“1350574775”格式,请尝试此操作:

private void onCreate(Bundle bundle){
    ....
    String S = "1350574775";

    //convert unix epoch timestamp (seconds) to milliseconds
    long timestamp = Long.parseLong(s) * 1000L; 
    czas.setText(getDate(timestamp ));  
}



private String getDate(long timeStamp){

    try{
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "xx";
    }
} 

答案 1 :(得分:6)

String S = "1350574775";

您将以秒为单位发送时间戳,而不是毫秒。

这样做,而不是:

String S = "1350574775000";

,在您的getDate方法中,乘以1000L

new Date(Long.parseLong(timeStampStr) * 1000L)

答案 2 :(得分:0)

 public static String getTime(long timeStamp){
    try{
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeStamp * 1000);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
        Date date = (Date) calendar.getTime();
        return sdf.format(date);
    }catch (Exception e) {
    }
    return "";
}