需要在Java中获取当前时间戳

编程入门 行业动态 更新时间:2024-10-26 00:21:10
本文介绍了需要在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

我需要它是Threadsafe。

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()));

或链接这里。

推荐答案

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的,以便能够存储或在SQL数据库中检索 TIMESTAMP / DATETIME 列类型,并将其从/转换为 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中获取当前时间戳

本文发布于:2023-11-24 12:23:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!