2008-10-22 3 views
7

¿Cómo puedo transformar un valor de tiempo en formato YYYY-MM-DD en Java?¿Cómo transformar un valor de tiempo en formato YYYY-MM-DD en Java?

long lastmodified = file.lastModified(); 
String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ 
+0

¿Quieres decir AAAA-MM-DD? –

+0

sí, he editado la pregunta. Año = Año en español –

+0

posible duplicado de [Cómo obtener la hora actual en formato YYYY-MM-DD HH: MI: Sec.Millisegundo en Java?] (Http://stackoverflow.com/questions/1459656/how-to -get-the-current-time-in-aaaa-mm-dd-hhmisec-milisegundo-format-in-java) – Raedwald

Respuesta

25

Algo así como:

Date lm = new Date(lastmodified); 
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm); 

consulte el Javadoc de SimpleDateFormat.

+0

Solo para indicar lo obvio aquí, si estás haciendo esto en el contexto de un objeto de larga vida o en un bucle, es probable que desee construir el objeto SimpleDateFormat una vez y reutilizarlo. – nsayer

+1

Aunque tenga cuidado: SimpleDateFormat no es seguro para subprocesos –

3
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(new Date(lastmodified)); 

Busca el patrón correcto que desea para SimpleDateFormat ... Me pueden haber incluido el incorrecto de la memoria.

0
Date d = new Date(lastmodified); 
DateFormat form = new SimpleDateFormat("yyyy-MM-dd"); 
String lasmod = form.format(d); 
+0

Minúscula 'mm' es el minuto. – sblundy

4
final Date modDate = new Date(lastmodified); 
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); 
final String lasmod = f.format(modDate); 

SimpleDateFormat

1

Probar:

import java.text.SimpleDateFormat; 
import java.util.Date; 

long lastmodified = file.lastModified(); 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
String lastmod = format.format(new Date(lastmodified)); 
Cuestiones relacionadas