The title of the question mentions "current date and time", but in the body of the question specific values are mentioned. Anyway, there is a solution for both.
The other responses use SimpleDateFormat
, but from Java 8, you can use the API% com_of% . In this API, there are classes to manipulate just the date, or just the time, which seems to be what you need.
To read the java.time
mentioned, you can use Strings
, which turns java.time.format.DateTimeFormatter
into the corresponding type ( String
for dates, or java.time.LocalDate
for hours).
Then, I use another java.time.LocalTime
to format them (convert to another format):
// converter 23062017 para 23/06/2017
DateTimeFormatter parserData = DateTimeFormatter.ofPattern("ddMMuuuu");
LocalDate data = LocalDate.parse("23062017", parserData);
DateTimeFormatter formatterData = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dataFormatada = formatterData.format(data); // 23/06/2017
// converter 212010 para 21:20:10
DateTimeFormatter parserHora= DateTimeFormatter.ofPattern("HHmmss");
LocalTime hora = LocalTime.parse("212010", parserHora);
DateTimeFormatter formatterHora = DateTimeFormatter.ofPattern("HH:mm:ss");
String horaFormatada = formatterHora.format(hora); // 21:20:10
If you want to use the current date and time, you can use a DateTimeFormatter
(which already has both information) and format it:
// data/hora atual
LocalDateTime agora = LocalDateTime.now();
// formatar a data
DateTimeFormatter formatterData = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dataFormatada = formatterData.format(agora);
// formatar a hora
DateTimeFormatter formatterHora = DateTimeFormatter.ofPattern("HH:mm:ss");
String horaFormatada = formatterHora.format(agora);
If you do not already use Java 8, you can use ThreeTen Backport , which has the same classes already mentioned and works basically the same way. The difference is that they are in the package LocalDateTime
(instead of org.threeten.bp
).
The backport is compatible with JDK 6 and 7.
If you can use this API instead of java.time
and Date
, do so. The new API is far superior and fixes several existing problems in the old API .