How to get and format current date and time?

Asked

Viewed 23,968 times

3

I would like to know how to get the current date and time and then format them in JAVA.

For example, I have these two values:

23062017 
212010

I want to store each value in a variable, and then I want to format it this way:

23/06/2017 
21:20:10

5 answers

6

In the question title is mentioned "date and current time", but in the question body specific values are mentioned. Anyway, it follows a solution for both.


The other answers use SimpleDateFormat, but from Java 8, you can use the API java.time. In this API, there are classes to only manipulate the date, or just the time, which seems to be what you need.

To read the Strings mentioned, you can use a java.time.format.DateTimeFormatter, that transforms the String in the corresponding type (java.time.LocalDate for dates, or java.time.LocalTime for hours).

Then I use another DateTimeFormatter to format them (convert to other 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 java.time.LocalDateTime (who already owns 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);

Also note that in the java.time it is possible to use u instead of y for the year. The difference is that the y does not work for AC (Before Christ) dates. How u works for both cases (AC and DC), ends up being the best choice. See this reply from Soen to better understand the details.


If you don’t already use Java 8, you can use Threeten Backport, that has the same classes already mentioned and works basically the same way. The difference is that they are in the package org.threeten.bp (instead of java.time).

Backport is compatible with JDK 6 and 7.

If you can use this API instead of Date and SimpleDateFormat, do so. The new API is far superior and fixes several of the problems existing in the old API.


If you are attached to Java 5 for any reason, you cannot use Threeten Backport. But if you want to use a better API than Date and SimpleDateFormat, one option is to use the Joda-Time. She looks a lot like java.time (for she is his predecessor, and both were made by the same person), despite there are some differences between them.

But the idea is essentially the same, see how to convert your strings to a date and time in the desired format:

import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

// converter 23062017 para 23/06/2017
DateTimeFormatter parserData = DateTimeFormat.forPattern("ddMMyyyy");
LocalDate data = LocalDate.parse("23062017", parserData);
DateTimeFormatter formatterData = DateTimeFormat.forPattern("dd/MM/yyyy");
String dataFormatada = formatterData.print(data);
System.out.println(dataFormatada); // 23/06/2017

// converter 212010 para 21:20:10
DateTimeFormatter parserHora = DateTimeFormat.forPattern("HHmmss");
LocalTime hora = LocalTime.parse("212010", parserHora);
DateTimeFormatter formatterHora = DateTimeFormat.forPattern("HH:mm:ss");
String horaFormatada = formatterHora.print(hora);
System.out.println(horaFormatada); // 21:20:10

The idea is the same: use a org.joda.time.format.DateTimeFormatter to convert the strings to a org.joda.time.LocalDate (representing the date - only the day, month and year) and for a org.joda.time.LocalTime (a schedule).

Then use another one DateTimeFormatter to convert the LocalDate and the LocalTime to another format. A difference to the java.time is that in the Joda-Time classes it is also possible to use toString() with the desired format:

System.out.println(data.toString("dd/MM/yyyy")); // 23/06/2017
System.out.println(hora.toString("HH:mm:ss")); // 21:20:10

And to get the current date/time, one can build a org.joda.time.LocalDateTime, that already has both date and time, and from there print in the 2 formats:

LocalDateTime dataHoraAtual = new LocalDateTime();
System.out.println(dataHoraAtual.toString("dd/MM/yyyy"));
System.out.println(dataHoraAtual.toString("HH:mm:ss"));

Just remembering that Joda-Time is an alternative to JDK 5, since on its own site there’s a warning saying that this API is a "shut down" project, there are no improvements planned and finally recommends the use of java.time (namely the Threeten Backport for JDK 6 and 7, and java.time for JDK >= 8).


This does not invalidate the other answers they use SimpleDateFormat and Date. If you can’t use Java >= 8, or you can’t add a library like Threeten Backport or Joda-Time, the legacy API remains a valid option.

5

To recover the current system date and time you can do:

Date dataHoraAtual = new Date();
String data = new SimpleDateFormat("dd/MM/yyyy").format(dataHoraAtual);
String hora = new SimpleDateFormat("HH:mm:ss").format(dataHoraAtual);

This way you will receive the date and time in the formats you want and in separate variables.


For reference, in my Github has a class (a Servlet) I made for a college job that returns the date and time.

  • 1

    good response, but do not point out external links, preferably by copying the content here and just reference the original source ...

  • 3

    @pmargreff but it is as reference. I even wrote exactly: "For reference". The answer is what is on top of the horizontal line ._.

1

Opa, blza!?

You can get the current date of the classic Apis (Date), and also the new java 8 date and time Apis (LocalDateTime and LocalDate).

Classical API

to the java.util.Date:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //01/02/2019 14:08:43

Java 8+

to the java.time.LocalDateTime:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //01/02/2019 14:08:43

to the java.time.LocalDate:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //01/02/2019

1

In this example generates two day and hour strings, with the format for day 02-03-2018 and time string 22:21:30

Calendar calendar = Calendar.getInstance();//cria o obj calendar e atribui a hora e data do sistema
Date data = calendar.getTime();//transforma o obj calendar em obj Date

SimpleDateFormat sddia = new SimpleDateFormat("dd-MM-yyyy");//cria um obj de formatação de data
SimpleDateFormat sdhora = new SimpleDateFormat("HH:mm:ss");//cria um obj de formatação de hora
String dia = sddia.format(data);//gera a string final formatada no estilo "dd-MM-yyyy"
String hora = sdhora.format(data);//gera a string final formatada no estilo "HH:mm:ss"
  • Just one detail, to get the current date, it’s simpler to do Date data = new Date(). Create a Calendar only for that is unnecessary, because new Date() already gets the current system date and time :-)

0

public static void main(String[] args) {

    String dataAtualFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
                                    .format(System.currentTimeMillis());

    //Seta valores da data
    String dataString = dataAtualFormatada.substring(0,10);

    //Seta valores do horário
    String horario = dataAtualFormatada.substring(11,19);     

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.