Question

Quel est le meilleur moyen d’analyser une date dans l’un des formats suivants

 "dd-MM-yyyy HH:mm"
 "dd/MM/yyyy HH:mm"
 "dd.MM.yyyy HH:mm"

sans créer 3 SimpleDateFormats et analyser chacun d'eux.

Merci

Était-ce utile?

La solution

Il est probablement plus facile de "modifier". la chaîne source dans un format canonique:

if (text.length() == 16)
{
    if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
        (text.charAt(2) == '.' && text.charAt(5) == '.'))
    {
        text = text.substring(0, 2) + "-" + text.substring(3, 5) 
           + "-" + text.substring(6);
    }
}

Utilisez ensuite la chaîne de format en utilisant "- -".

Notez que ceci est très spécifique, ne remplaçant que exactement les caractères qui vous intéressent, pour éviter les effets secondaires indésirables.

Autres conseils

Pourriez-vous d'abord exécuter deux opérations de remplacement afin de réduire les trois formats à un seul?

Vous pouvez utiliser Date de début commun pour Apache DateUtils.parseDate

import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;

public class Test {

public static void main(String[] args) throws ParseException {

    String[] values = new String[]{"31-12-2009 12:00", "31/12/2009 12:00", "31.12.2009 12:00"};
    String[] parsePatterns = new String[]{"dd-MM-yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd.MM.yyyy HH:mm"};

    for (String value : values) {
        System.out.println(DateUtils.parseDate(value, parsePatterns));
    }
}
}

Eh bien, en interne, cela crée SimpleDateFormats, mais qu'est-ce qui ne va pas avec ça?

que diriez-vous d'une regex:

"\\d\\d[./-]\\d\\d[./-]\\d\\d\\d\\d \\d\\d:\\d\\d"

Dans le code, cela voudrait dire quelque chose comme ceci:

Pattern pattern = 
Pattern.compile("(\\d\\d)([./-])(\\d\\d)([./-])(\\d\\d\\d\\d) (\\d\\d):(\\d\\d)");

Matcher matcher = 
pattern.matcher("31-07-1983 15:30");

if (matcher.find() && matcher.group(2).equals(matcher.group(4))) {
  int day = Integer.parseInt(matcher.group(1));
  int month = Integer.parseInt(matcher.group(3));
  int year = Integer.parseInt(matcher.group(5));
  int hour = Integer.parseInt(matcher.group(6));
  int minute = Integer.parseInt(matcher.group(7));
} 

Faites-le vous-même avec une expression régulière:

public class SpecialDateFormat
{
    private final static Pattern PATTERN = Pattern.compile("(\\d{2})[\\.\\/\\-](\\d{2})[\\.\\/\\-](\\d{4}) (\\d{2}):(\\d{2})");

    public static Date parse(String text) throws ParseException {
        Matcher m = PATTERN.matcher(text);
        if (m.matches()) {
            int dd = Integer.parseInt(m.group(1));
            int mm = Integer.parseInt(m.group(2));
            int yy = Integer.parseInt(m.group(3));
            int hh = Integer.parseInt(m.group(4));
            int mi = Integer.parseInt(m.group(5));

            // NOTE: Checking if values are in valid ranges omitted

            Calendar cal = Calendar.getInstance();
            cal.set(yy, mm - 1, dd, hh, mi, 0);

            return cal.getTime();
        }
        else {
            throw new ParseException("Unparseable date: " + text, 0);
        }
    }
}

Notez cependant que cela permet de mélanger différents séparateurs, par ex. 17-09 / 2009 12: 00 " serait autorisé.

ParseExact peut prendre un tableau de formats. Vous devez toujours spécifier tous les formats, mais l'opération ne nécessite qu'une seule opération.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top