2012-12-27 16 views
33

Voglio l'ora corrente in millis e quindi archiviarlo in formato 12 ore ma con questo pezzo di codice sto ricevendo il formato di 24 ore.SimpleDateFormat restituisce la data di 24 ore: come ottenere la data di 12 ore?

long timeInMillis = System.currentTimeMillis(); 
Calendar cal1 = Calendar.getInstance(); 
cal1.setTimeInMillis(timeInMillis); 
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss a"); 
dateforrow = dateFormat.format(cal1.getTime()); 

qualcuno può suggerire modifiche per ottenere i risultati desiderati?

+4

(primo posto dove guardare è l'API Inoltre, cercare di riassumere la questione nel titolo migliore:.. Si fa una grande prima impressione) –

risposta

103

Change HH-hh come

long timeInMillis = System.currentTimeMillis(); 
Calendar cal1 = Calendar.getInstance(); 
cal1.setTimeInMillis(timeInMillis); 
SimpleDateFormat dateFormat = new SimpleDateFormat(
           "dd/MM/yyyy hh:mm:ss a"); 
dateforrow = dateFormat.format(cal1.getTime()); 

Nota che dd/mm/yyyy - vi darà minuti al posto del mesi.

0
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a"); 

uso hh in luogo di HH

29

Riferendosi alla SimpleDataFormat JavaDoc:

Letter | Date or Time Component | Presentation | Examples 
--------------------------------------------------------- 
    H | Hour in day (0-23) | Number | 0 
    h | Hour in am/pm (1-12) | Number | 12 
+0

String getCurrentTimeStamp privato () { SimpleDateFormat timestamp = new SimpleDateFormat ("yyyyMMddHHmmss"); return timestamp.format (new Date()); }. questo darà il tuo 24 ore ..... in caso di aaaaMMggmhmmss restituirà il formato 12 ore. – PrinceMidha

4

Hi I testato sotto il codice che funzionava bene:

long timeInMillis = System.currentTimeMillis(); 
    Calendar cal1 = Calendar.getInstance(); 
    cal1.setTimeInMillis(timeInMillis); 
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a"); 
    dateFormat.format(cal1.getTime()); 
3

Sì, ha confermato che il semplice utilizzo hh invece di HH ha risolto il mio problema.

Modificato da questo:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa"); 

A tal:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa"); 

è comunque possibile utilizzare HH per memorizzare il tempo se non si vuole disturbare l'archiviazione e trattare con il AM/PM . Quindi quando lo recuperi, usa hh.

-1

vedi esempio codice qui sotto:

SimpleDateFormat df = new SimpleDateFormat("hh:mm"); 
String formattedDate = df.format(new Date()); 
out.println(formattedDate); 
4

I ri-incontrare questo nel modo più duro pure. H vs h, per 24 ore contro 12 ore!

1

Si può provare in questo modo

Calendar c= Calendar.getInstance(); 

    SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a"); 
    String str=sdf.format(c.getTime()); 
Problemi correlati