Need to get current timestamp in Java(需要在 Java 中获取当前时间戳)
问题描述
我需要在Java中获取当前时间戳,格式为MM/DD/YYYY h:mm:ss AM/PM
,
I need to get the current timestamp in Java, with the format of MM/DD/YYYY h:mm:ss AM/PM
,
例如:06/01/2000 10:01:50 AM
我也需要它是线程安全的.
I need it to be Threadsafe as well.
我可以使用这样的东西吗?
Can I utilize something like this?
java.util.Date date = new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
或者链接中讨论的示例这里.
Or the examples discussed at the link here.
推荐答案
SimpleDateFormat
的线程不安全应该不是问题,如果您只是在使用它的同一个方法块中创建它.换句话说,您不将其分配为类的静态变量或实例变量,并在一个或多个可由多个线程调用的方法中重用它.只有这样 SimpleDateFormat
的线程不安全性才会暴露.但是,您可以在同一个方法块中安全地重用相同的 SimpleDateFormat
实例,因为它只能由当前线程访问.
The threadunsafety of SimpleDateFormat
should not be an issue if you just create it inside the very same method block as you use it. In other words, you are not assigning it as static or instance variable of a class and reusing it in one or more methods which can be invoked by multiple threads. Only this way the threadunsafety of SimpleDateFormat
will be exposed. You can however safely reuse the same SimpleDateFormat
instance within the very same method block as it would be accessed by the current thread only.
此外,您在其中使用的 java.sql.Timestamp
类不应被滥用,因为它特定于 JDBC API,以便能够存储或检索 TIMESTAMP
/DATETIME
列类型在 SQL 数据库中并将其从/转换为 java.util.Date
.
Also, the java.sql.Timestamp
class which you're using there should not be abused as it's specific to the JDBC API in order to be able to store or retrieve a TIMESTAMP
/DATETIME
column type in a SQL database and convert it from/to java.util.Date
.
所以,应该这样做:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 12/01/2011 4:48:16 PM
这篇关于需要在 Java 中获取当前时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:需要在 Java 中获取当前时间戳


基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01