日期到 Unix 时间戳
Date to Unix timestamp
我有一个看起来像 "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);
我认为您可以在 Whosebug 上搜索答案,而不是发布新问题,因为它使 Whosebug 变得更好,我只是快速搜索了一下,它们是:
Getting unix timestamp from Date()
或者这里是直接的代码:
Date currentDate = new Date();
currentDate.getTime() / 1000;
最近,人们更喜欢 jodaTime:
DateTime dateTime = new DateTime();
long unix = dateTime.getMillis()/1000;
我有一个看起来像 "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);
我认为您可以在 Whosebug 上搜索答案,而不是发布新问题,因为它使 Whosebug 变得更好,我只是快速搜索了一下,它们是: Getting unix timestamp from Date()
或者这里是直接的代码:
Date currentDate = new Date();
currentDate.getTime() / 1000;
最近,人们更喜欢 jodaTime:
DateTime dateTime = new DateTime();
long unix = dateTime.getMillis()/1000;