Convertir java.útil.Fecha a Cadena


Quiero convertir un objeto java.util.Date a un String en Java.

El formato es 2010-05-30 22:15:52

Author: Vadzim, 2011-04-16

16 answers

En Java, Convierte una Fecha a una cadena usando una cadena de formato:

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

// Get the date today using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);

De http://www.kodejava.org/examples/86.html

 696
Author: alibenmessaoud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-22 22:16:51
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
 198
Author: Charlie Salts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-16 01:02:29

Commons-lang Formulario de datos está lleno de golosinas (si tienes commons-lang en tu classpath)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
 56
Author: webpat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-10 10:25:51

Tl; dr

myUtilDate.toInstant()  // Convert `java.util.Date` to `Instant`.
          .atOffset( ZoneOffset.UTC )  // Transform `Instant` to `OffsetDateTime`.
          .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String.
          .replace( "T" , " " )  // Put a SPACE in the middle.

2014-11-14 14:05:09

Java.tiempo

La forma moderna es con java.clases de tiempo que ahora suplantan a las problemáticas clases de fecha y hora heredadas.

Primero convierte tu java.util.Date a un Instant. El Instant clase representa un momento en la línea de tiempo en UTC con una resolución de nanosegundos (hasta nueve (9) dígitos de una fracción decimal).

Conversiones a/desde java.el tiempo es realizado por nuevos métodos añadidos a las clases antiguas.

Instant instant = myUtilDate.toInstant();

Tanto tu java.util.Date como java.time.Instant están en UTC. Si quieres ver la fecha y la hora como UTC, que así sea. Llame a toString para generar una cadena en formato estándar ISO 8601.

String output = instant.toString();  

2014-11-14T14:05:09Z

Para otros formatos, necesita transformar su Instant en el más flexible OffsetDateTime.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

Odt.toString(): 2014-11-14T14:05:09+00:00

Para obtener una cadena en el formato deseado, especifique una DateTimeFormatter. Puede especificar un formato personalizado. Pero usaría uno de los formateadores predefinidos (ISO_LOCAL_DATE_TIME), y reemplace el T en su salida con un ESPACIO.

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

Por cierto, no recomiendo este tipo de formato donde se pierde deliberadamente la offset-from-UTC o información de zona horaria. Crea ambigüedad en cuanto a el significado del valor fecha-hora de esa cadena.

También tenga cuidado con la pérdida de datos, ya que cualquier segundo fraccional está siendo ignorado (efectivamente truncado) en la representación de su Cadena del valor fecha-hora.

Para ver ese mismo momento a través de la lente de la hora del reloj de pared de una región en particular, aplique un ZoneId para obtener un ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

Zdt.toString (): 2014-11-14T14:05: 09-05: 00[America/Montreal]

Para generar una cadena formateada, haga el igual que el anterior, pero sustitúyase odt por zdt.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

Si ejecuta este código un número muy grande de veces, es posible que desee ser un poco más eficiente y evitar la llamada a String::replace. Dejar caer esa llamada también hace que su código sea más corto. Si lo desea, especifique su propio patrón de formato en su propio objeto DateTimeFormatter. Almacene esta instancia en caché como constante o miembro para reutilizarla.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );  // Data-loss: Dropping any fractional second.

Aplicar ese formateador pasando el instancia.

String output = zdt.format( f );

Acerca de java.tiempo

El java.time framework está integrado en Java 8 y versiones posteriores. Estas clases suplantan a las clases de fecha y hora antiguas y problemáticas, como java.util.Date, .Calendar, & java.text.SimpleDateFormat.

El proyecto Joda-Time, ahora en modo de mantenimiento , aconseja la migración a java.tiempo.

Para obtener más información, consulte el Tutorial de Oracle . Y desbordamiento de pila de búsqueda para muchos ejemplos y explicacion.

Gran parte de java.la funcionalidad de tiempo se vuelve a portar a Java 6 y 7 en ThreeTen-Backport y se adapta a Android en ThreeTenABP (ver Cómo usar...).

El proyecto ThreeTen-Extra extiende java.tiempo con clases adicionales. Este proyecto es un campo de pruebas para posibles adiciones futuras a Java.tiempo.

 18
Author: Basil Bourque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:20

Altenative one-liners in plain-old java:

String.format("The date: %tY-%tm-%td", date, date, date);

String.format("The date: %1$tY-%1$tm-%1$td", date);

String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

Esto utiliza Formatter y indexación relativa en lugar de SimpleDateFormat que es no thread-safe, por cierto.

Un poco más repetitivo, pero necesita solo una declaración. Esto puede ser útil en algunos casos.

 13
Author: Vadzim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-20 12:42:43

¿Por qué no usas Joda (org.joda.tiempo.DateTime)? Es básicamente de una sola línea.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09
 9
Author: dbow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-15 00:14:47

Parece que estás buscando SimpleDateFormat.

Formato:aaaa-MM-dd kk:mm: ss

 7
Author: pickypg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-16 01:01:54
public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}
 4
Author: Ashish Tiwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-31 06:31:29

La forma más fácil de usarlo es la siguiente:

currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");

Donde "aaaa-MM-dd'T'HH: mm: ss" es el formato de la fecha de lectura

Salida: Dom Abr 14 16:11:48 EEST 2013

Notas: HH vs hh - HH se refiere al formato de tiempo 24h - hh se refiere al formato de hora 12h

 4
Author: Rami Sharaiyri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-22 12:24:27

Si solo necesita la hora a partir de la fecha, solo puede usar la función de Cadena.

Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );

Esto cortará automáticamente la parte de tiempo de la cadena y la guardará dentro de timeString.

 4
Author: funaquarius24,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-07 08:03:02

Aquí hay ejemplos del uso de la nueva Java 8 Time API para formatear legado java.util.Date:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

Es bueno acerca de DateTimeFormatter que se puede almacenar en caché de manera eficiente, ya que es seguro para subprocesos (a diferencia de SimpleDateFormat).

Lista de fomatters predefinidos y referencia de la notación del patrón.

Créditos:

¿Cómo analizar / formatear fechas con LocalDateTime? (Java 8)

Java8 java.útil.Conversión de fecha a java.tiempo.ZonedDateTime

Formato Instant to String

¿Cuál es la diferencia entre java 8 ZonedDateTime y OffsetDateTime?

 3
Author: Vadzim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:33

Prueba esto,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Date
{
    public static void main(String[] args) 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = "2013-05-14 17:07:21";
        try
        {
           java.util.Date dt = sdf.parse(strDate);         
           System.out.println(sdf.format(dt));
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }
    }
}

Salida:

2013-05-14 17:07:21

Para obtener más información sobre el formato de fecha y hora en java, consulte los enlaces a continuación

Centro de ayuda de Oracle

Ejemplo de fecha y hora en java

 2
Author: Shiva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-06 11:38:52

En un solo disparo;)

Para obtener la Fecha

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

Para obtener la Hora

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

Para obtener la fecha y la hora

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

Feliz codificación:)

 2
Author: S.D.N Chanaka Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-03 20:43:11
public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}
 1
Author: Artanis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 21:41:22

Probemos esto

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

O una función de utilidad

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

Desde Convertir la fecha en Cadena en Java

 1
Author: David Pham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-26 16:25:09
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = "2010-05-30 22:15:52";
    java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
    System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
 1
Author: Dulith De Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 14:52:16