2012-06-28 18 views
14

Ho un String contenente il risultato di toString() chiamato su un'istanza di java.util.Date. Come posso analizzare questo valore su un oggetto Date?Analisi di un java Data indietro da toString()

documenti Java dicono che toString() converte questo oggetto Date ad un String della forma:

dow mon dd hh:mm:ss zzz yyyy 

ma naturalmente non c'è nessuna tale tag formato "dow" o "mon".

Qualcuno potrebbe aiutarmi con questo problema. Si prega di notare che sfortunatamente la chiamata toString() è in un pezzo di codice fuori dal mio controllo.

+2

possibile duplicato di [come analizzare l'uscita di new Date(). ToString()] (http : //stackoverflow.com/questions/4713825/how-to-parse-output-of-new-date-tostring) –

risposta

27

È necessario utilizzare SimpleDateFormat anziché data.toString(). In questo modo avrai il controllo sul formato che desideri utilizzare.

Date date = new Date(); 

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Or whatever format fits best your needs. 
String dateStr = sdf.format(date); 

Allora avete la stringa è possibile analizzare di nuovo a una data ...

Date date2 = sdf.parse(dateStr); 

di utilizzare il formato toString() è necessario impostare l'impostazione internazionale SimpleDateFormat di inglese e utilizzare il formato : "EEE MMM dd HH:mm:ss Z yyyy".

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));` 
+0

Mm..come ho detto, non ho alcun controllo su toString(), dato che è fatto da Struts. Ad ogni modo, impostare la localizzazione EN fa il trucco, quindi grazie. Devo solo notare che la stringa di formato corretta è "EEE MMM dd HH: mm: ss zzz yyyy", hai dimenticato il mese. – prepetti

+0

Ho modificato la risposta per averlo. :) –

-1

Suppsoe ottieni String di "dateString";

SimpleDateFormat sdf = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy"); 

Date date = sdf.parse("dateString"); 
+0

Questo non funziona e si traduce in un'eccezione generata.La chiamata corretta del costruttore è: 'SimpleDateFormat sdf = new SimpleDateFormat (" EEE MMM dd HH: mm: ss Z yyyy ", nuovo Locale (" us "));' – sizzle

0

In primo luogo dare un'occhiata a tutti i formati di data forniti da Java Date Formats. E puoi usare la classe per fare ciò che vuoi.

public class DateFormatTest 
    { 
     public DateFormatTest() 
     { 
     String dateString = // in "dow mon dd hh:mm:ss zzz yyyy" format 

     SimpleDateFormat dateFormat = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy"); 
     Date convertedDate = dateFormat.parse(dateString); 

     System.out.println("Converted string to date : " + convertedDate); 
     } 

     public static void main(String[] argv) 
     { 
     new DateFormatTest(); 
     } 
    } 
    }