我有一個看起來像「2015-06-07 16:01:33.0」的字符串。我想將它轉換成一個unix時間戳。首先,我使用Calendar
實用程序將其轉換爲Date
對象。我如何將日期轉換爲紀元時間?日期到Unix時間戳
String origintime = "2015-06-07 16:01:33.0";
String year = origintime.split(" ")[0].split("-")[0];
String month = origintime.split(" ")[0].split("-")[1];
String day = origintime.split(" ")[0].split("-")[2];
String hour = origintime.split(" ")[1].split(":")[0];
String mins = origintime.split(" ")[1].split(":")[1];
String secs = origintime.split(" ")[1].split(":")[2].replace(".0","");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
cal.set(Calendar.MONTH, Integer.parseInt(month));
cal.set(Calendar.YEAR, Integer.parseInt(year));
cal.set(Calendar.HOUR_OF_DAY,Integer.parseInt(hour));
cal.set(Calendar.MINUTE,Integer.parseInt(mins));
cal.set(Calendar.SECOND,Integer.parseInt(secs));
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
可能重複的[從日期()獲取unix時間戳](http://stackoverflow.com/questions/7784421/getting-unix-timestamp-from-date) – Stefan
請在發佈之前搜索StackOverflow。這個話題之前已經被很多次討論過了。 –