Java日期和时间戳互转(看这一篇就够了)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IOTestMain {
public static void main(String[] args) throws ParseException {
System.out.println(System.currentTimeMillis());
System.out.println(date2long("2021", "09", "29", "14", "55", "03"));
System.out.println(long2date(date2long("2021", "09", "29", "14", "55", "03")));
}
public static long date2long(String year, String month, String day, String hour, String minutes, String sec) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(year);
stringBuilder.append("/");
stringBuilder.append(month);
stringBuilder.append("/");
stringBuilder.append(day);
stringBuilder.append(" ");
stringBuilder.append(hour);
stringBuilder.append(":");
stringBuilder.append(minutes);
stringBuilder.append(":");
stringBuilder.append(sec);
String sDt = stringBuilder.toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dt = null;
try {
dt = sdf.parse(sDt);
if (dt != null) {
return dt.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return -1L;
}
public static String long2date(long timestamp) throws ParseException {
Date date = new Date();
date.setTime(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
}
输出:
1632972081606
1632898503000
2021-09-29 14:55:03
Process finished with exit code 0