How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
To get the current timestamp in string format in Java, you can use the SimpleDateFormat
class and specify the desired format string. Here's an example of how you can get the current timestamp in the "yyyy.MM.dd.HH.mm.ss" format:
import java.text.SimpleDateFormat;
import java.util.Date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
String timestamp = dateFormat.format(new Date());
In this example, a SimpleDateFormat
object is created with the "yyyy.MM.dd.HH.mm.ss" format string. The format
method of the SimpleDateFormat
class is then used to format the current date (obtained using the new Date()
constructor) as a string.
Here's a breakdown of the format string "yyyy.MM.dd.HH.mm.ss":
yyyy
: the year with century as a decimal numberMM
: the month as a decimal number (01-12)dd
: the day of the month as a decimal number (01-31)HH
: the hour of the day as a decimal number (00-23)mm
: the minute as a decimal number (00-59)ss
: the second as a decimal number (00-59)
The resulting string will have the form "YYYY.MM.DD.HH.MM.SS", where YYYY is the year, MM is the month, DD is the day, HH is the hour, MM is the minute, and SS is the second.
Keep in mind that the SimpleDateFormat
class is not thread-safe, so you should not use a single instance of the class from multiple threads concurrently. If you need to use the SimpleDateFormat
class from multiple threads, you should either create a new instance of the class for each thread, or use a thread-safe alternative such as the DateTimeFormatter
class introduced in Java 8.