用Java生成当前的日期戳

时间:2020-03-06 14:24:29  来源:igfitidea点击:

用Java生成当前日期戳的最佳方法是什么?

YYYY-MM-DD:hh-mm-ss

解决方案

Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);

SimpleDateFormatter是我们想要的。

还有

long timestamp = System.currentTimeMillis()

这是new Date()(@John Millikin)在内部使用的。一旦有了它,就可以按照自己的喜好对其进行格式化。

final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh-mm-ss");

formatter.format(new Date());

用于SimpleDateFormat的JavaDoc提供有关日期和时间模式字符串的信息。

使用标准的JDK,我们将要使用java.text.SimpleDateFormat

Date myDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
String myDateString = sdf.format(myDate);

但是,如果我们可以选择使用Apache Commons Lang软件包,则可以使用org.apache.commons.lang.time.FastDateFormat

Date myDate = new Date();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");
String myDateString = fdf.format(myDate);

FastDateFormat具有线程安全的优点,因此我们可以在整个应用程序中使用单个实例。它仅用于格式化日期,不像下面的示例中的SimpleDateFormat那样支持解析:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
Date yourDate = sdf.parse("2008-09-18:22-03-15");