2012-11-05 132 views
16

我不知道如何将时间戳转换为日期。 我:时间戳到字符串日期

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日,但它是错误的。

回答

48

试试这个,如果你用 “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

这不是工作w ith我必须改变1000 - > 1000L。 –

+0

感谢@PinoyCoder,它解决了我! –

+0

谢谢,这个答案解决了我的问题。但如何得到这个日期的 2017年7月22日 –

4
String S = "1350574775"; 

您正在以秒为单位发送您的时间戳,而不是毫秒。通过1000L

String S = "1350574775000"; 

或者,在你getDate方法,乘法:

做到这一点,而不是

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