How to convert a string to date or date?

Asked

Viewed 9,539 times

5

I have here the statements I need to convert from string to date, can help me?

ObjAl.setDataEmissao(TxtDataEmissao.getText());
ObjAl.setDataNascimento(TxtDataNascimento.getText());

4 answers

5

There is the DateTimeFormatter.

Using it it is possible to convert a string into an object LocalDate, which is part of the new Java Date API, an example:

String data = "13 Janeiro 2016";

DateTimeFormatter format = DateTimeFormatter.ofPattern("d MMMM yyyy");
LocalDate localDate = LocalDate.parse(data, format);

Accepted standards can be found in Javadoc, although they are nothing new to those who work with dates in Java.

Having the localDate, we can manipulate the object to, for example, obtain the day of the week:

String diaDaSemana = localDate.getDayOfWeek()
                              .getDisplayName(TextStyle.FULL, Locale.getDefault()); 

System.out.println(diaDaSemana); // Quarta-feira

The new Java Date API is inspired by Joda and its main goal is to work with dates and times.

Unlike an object Date representing an instant in the timeline, stored in a long counting milliseconds since midnight 1970.

If you really need to work with milliseconds, go from Date or Instant. But if you want to work simply with time objects, be cool and use the new api.

  • The LocalDate is there to manipulate dates exclusively.
  • If you only want to work with time/time, there is LocalTime.
  • If you need the date and time, there’s the LocalDateTime.

Finally, we can transform the LocalDateTime in an object Date through the class Timestamp:

String data = "13 Janeiro 2016, 16:22";

DateTimeFormatter format = DateTimeFormatter.ofPattern("d MMMM yyyy, HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(data, format); 

Date d = Timestamp.valueOf(localDateTime);
System.out.println(d); // 2016-01-13 16:22:00.0

4

Something more or less like this:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date data = new java.sql.Date(format.parse(dataStr).getTime());

Remember to adapt to your need.

  • Thank you for the reply Otto, but how do I implement this code in my question? Porq if I were to convert a string to Integer, I would simply put Integer.parseint();

  • @yoly dataStr would be your Txtdataemissao.gettext() simlpes like this

  • Hamm! Now yes, I got it. Thanks :)

4

The SimpleDateFormat is intended to convert java.util.Date in String and vice versa.

When building this object it is possible to inform which date pattern you want to transform or recover.

If this pattern is not reported, the meadow shall be used by the Locale user’s.

Follow the class documentation.

Example of use:

public static void main(String[] args) {
        Date dataAtual = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

        String DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        DateToStr = format.format(dataAtual);
        System.out.println(DateToStr);

        try {
            Date strToDate = format.parse(DateToStr);
            System.out.println(strToDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

In your case, you should consider the format in which the TxtDataEmissao is displaying to instantiate your SimpleDateFormat:

 SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
// Verifique o formato!

    try {       
               ObjAl.setDataEmissao(format.parse(TxtDataEmissao.getText()));
       } catch (ParseException e) {
            e.printStackTrace();
       }

4

An Alternative would be to create a Class utilitarian with the methods that convert dates if you need to do conversions in more places. Or you can create the methods in the Class itself, Example:

    public static Date parseDate(String data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        return sdf.parse(data);
    }

    public static String parseDate(Date data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        return sdf.format(data);
    }

    public static java.sql.Date getSqlDate(Date data) {
        return new java.sql.Date(data.getTime());
    }   

Then just call these methods by passing a String or Date, this way:

//Converte String pra Date
ObjAl.setDataEmissao(parseDate(TxtDataEmissao.getText()));
  • 1

    This is a good way to avoid rewriting the same code everywhere! GO DRY CODE!

Browser other questions tagged

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