Need to get current timestamp in Java

后端 未结 10 1741
南旧
南旧 2020-12-25 09:47

I need to get the current timestamp in Java, with the format of MM/DD/YYYY h:mm:ss AM/PM,

For example: 06/01/2000 10:01:50 AM

I ne

10条回答
  •  执笔经年
    2020-12-25 10:22

    The fact that SimpleDateFormat is not thread-safe does not mean you cannot use it. What that only means is that you must not use a single (potentially, but not necessarily static) instance that gets accessed from several threads at once.

    Instead, just make sure you create a fresh SimpleDateFormat for each thread. Instances created as local variables inside a method are safe by definition, because they cannot be reached from any concurrent threads.

    You might want to take a look at the ThreadLocal class, although I would recommend to just create a new instance wherever you need one. You can, of course, have the format definition defined as a static final String DATE_FORMAT_PATTERN = "..."; somewhere and use that for each new instance.

提交回复
热议问题