【问题标题】:Date to Unix timestamp日期到 Unix 时间戳
【发布时间】:2015-07-13 09:42:35
【问题描述】:

我有一个看起来像 "2015-06-07 16:01:33.0" 的字符串。我想将其转换为 unix 时间戳。首先,我使用Calendar 实用程序将其转换为Date 对象。如何将日期转换为纪元时间?

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

【问题讨论】:

标签: java date calendar epoch


【解决方案1】:

我认为您可以在 StackOverflow 上搜索答案,而不是发布新问题,因为它使 StackOverflow 变得更好,我只是快速搜索了一下,它们是: Getting unix timestamp from Date()

或者这里是直截了当的代码:

Date currentDate = new Date();
currentDate.getTime() / 1000;

最近,人们更喜欢jodaTime:

DateTime dateTime = new DateTime();
long unix = dateTime.getMillis()/1000; 

【讨论】:

  • 发布重复问题的答案只会鼓励更多重复问题,并与您在第一句话中的建议相矛盾。相反,请使用您要求关闭此问题的 StackOverflow 功能。
  • 谢谢 Basil,我没有看到封闭式问题的功能!
猜你喜欢
  • 2010-10-02
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
相关资源
最近更新 更多