-1

I'm trying to convert a resultset from ddMMyyyy HH:mm:ss (ex: 19/06/2022 00:00:10) to yyyyMMddHHmmss (should be 20220619000010) with SimpleDateFormate without success. This is how I'm doing:

  1. I have an Util class, which has the follow class:
      public class Utils {
      public static String Format(String formato, Date date) {
        date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dataString = sdf.format(date);
        return dataString;
    }
 }

And I also have a ResultSet class witch return the objects of my query based in another class. Example:

Class one:

public class MyFile {
String Date = new String ();

+ getter and setter
}

Class 2 (create the line of my document):

public static MyFile createRow (ResultSet rs) throws SQLException {
MyFile mf = new MyFile();
mf.setDate(Utils.Format(rs.getString("Date");
return mf;
}

The point is: This conversion doesn't work and I can't find another way to do this. Someone could help me, please?

The java message:

"The method Format(String, Date) in te type Utils is not applicable for the arguments (String)
3 quick fixes available:
+ add argument to match 'Format(String, Date)'
- Change method 'Format(String, Date)': Remove parameter 'Date'
º Create method 'Format(String) in type 'Utils'"
Manuj0
  • 1
  • 2
  • 2
    Databases store __dates__, and dates _do not have a format in the first place_. That's just on the boundary when you interact with a user (format to print it, parse to read it). You need to pass a Date instance, or rather, a LocalDate instance. `Date` is a lie. it does not represent a date - hence, it is not suitable. – rzwitserloot Jun 20 '22 at 20:32
  • `date = new Date();` makes no sense. Why do you overwrite the date parameter with the current date? Also what's the purpose of `formato`? – akarnokd Jun 20 '22 at 20:33
  • 2
    In your database, is this a character-type column (such as a `varchar`) or a `Date` column? – Dawood ibn Kareem Jun 20 '22 at 20:58
  • 1
    I strongly recommend you don’t use `Date` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Use for example `LocalDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And if your SQL data type is `datetime`, use `rs.getObject("Date", LocalDateTime.class)` to retrieve it as a `LocalDateTime`. – Ole V.V. Jun 21 '22 at 04:35

4 Answers4

2

For the conversion, you'll need two SimpleDateFormats; one for parsing the string to date, another to turn the date to the desired format:

public static String Format(String formato, Date date) {
     SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
     try {
         date = new inputFormat.parse(formato);
     } catch (ParseException ex) {
         // wrong format?
     }
     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
     String dataString = sdf.format(date);
     return dataString;
}

// usage

mf.setDate(Utils.Format(rs.getString("Date"), new Date()));

I presume your date parameter would be a default Date in case the formato input string is invalid.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
1

If you want to do it with the packages java.time and java.time.format you can try something like this. Of course java.util.Date is stored essentially as milliseconds from the epoch without time zone, hence using UTC below. If you want the output to correspond to a particular time zone, then change it:

    public static String formatDate(Date d) {
        String result = null;
        Instant i = Instant.ofEpochMilli(d.getTime());
        ZonedDateTime zdt = ZonedDateTime.ofInstant(i, ZoneId.of("UTC"));
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        result = fmt.format(zdt);
        return result;
    }
g00se
  • 3,207
  • 2
  • 5
  • 9
  • No, `ZonedDateTime` is not the appropriate class as we have no time zone. Instead, use `OffsetDateTime` and the constant `ZoneOffset.UTC`. – Basil Bourque Jun 21 '22 at 07:05
  • I am expecting that a tz *will* be required in the end as otherwise a 'wrong' time will be displayed. – g00se Jun 21 '22 at 09:05
  • If a time zone is to be applied later, an `OffsetDateTime` object can easily be converted to a `ZonedDateTime` with a call to [`atZoneSameTime`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/OffsetDateTime.html#atZoneSameInstant(java.time.ZoneId)). Before reaching that point, use appropriate types to make the code clear and self-documenting. – Basil Bourque Jun 21 '22 at 16:53
0

First of all, I want to tell you that there are newer and more convenient libraries than the old java.util.Date library. I am not so experienced with the new ones, but mostly java.util.time (like here: Understanding Java util Date) or joda.time are recommended.

So maybe you want to consider using one of the newer library instead of the old SimpleDateFormat from java.util.Date, if you only just began coding with Dates and just picked the first library coming to your mind, I think it could be a good idea.

To your specific problem: The java error message just tells you how it is, in your utils class you have your String Format with the constructor with two input params, a String and a date. In this line:

mf.setDate(Utils.Format(rs.getString("Date");

you are calling your Utils.Format String, but you are only passing one argument, "rs.getString("Date")". So either you refactor your String Format Constructor to only take a string as an argument or you pass (like recommended in the java message) a string and a date, for instance like:

mf.setDate(Utils.Format(rs.getString("Date"), new Date();

While I'm writing this, I think in this line two closing brackets are missing. You should add them.

But I think it should not be that complicated to convert a String like 19/06/2022 00:00:10 into another format using SimpleDateFormat. All you need to do is

String sDate1="19/06/2022 00:00:10";
SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMddHHmmss"); 
Date date1=formatter1.parse(sDate1); 

This way, in date1 should be your DateString in the Format you specified when initialising your SimpleDateFormat formatter1. Here is the official doc to SimpleDateFormat: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Janosch
  • 84
  • 1
  • 6
  • 1
    That sDate1 conversion doesn't work. You need a pattern that matches `sDate1`, not the OPs desired output format. – akarnokd Jun 20 '22 at 20:46
0

Thnx for your answers, but I couldn't make any work. So, I tried another way with success. It is:

public static String Format (String date) {
    String formattedDate= date.substring(0, 4)
               + date.substring(5, 7)
               + date.substring(8, 10)
               + date.substring(11, 13)
               + date.substring(14, 16)
               + date.substring(17, 19);
    return formattedDate;
}
mf.setDate(Utils.Format(rs.getString("Date");
Manuj0
  • 1
  • 2