在 Java 中生成当前日期戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/99098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:02:22  来源:igfitidea点击:

Generate a current datestamp in Java

javadatestamp

提问by Trastle

What is the best way to generate a current datestamp in Java?

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

YYYY-MM-DD:hh-mm-ss

YYYY-MM-DD:hh-mm-ss

回答by jt.

Using the standard JDK, you will want to use java.text.SimpleDateFormat

使用标准 JDK,您将需要使用 java.text.SimpleDateFormat

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

However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat

但是,如果您可以选择使用 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 has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:

FastDateFormat 具有线程安全的优点,因此您可以在整个应用程序中使用单个实例。它严格用于格式化日期,并且不支持像 SimpleDateFormat 在以下示例中所做的解析:

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

回答by John Millikin

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

回答by sblundy

There's also

还有

long timestamp = System.currentTimeMillis() 

which is what new Date()(@John Millikin) uses internally. Once you have that, you can format it however you like.

这是new Date()(@ John Millikin)在内部使用的。一旦你有了它,你就可以随意格式化它。

回答by Walter Rumsby

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

formatter.format(new Date());

The JavaDoc for SimpleDateFormatprovides information on date and time pattern strings.

SimpleDateFormatJavaDoc提供有关日期和时间模式字符串的信息。

回答by Michael Neale

SimpleDateFormatter is what you want.

SimpleDateFormatter 就是你想要的。