Groovy java.sql.Timestamp.toString() a java.sql.Timestamp

I have this problem converting java.sql.Timestamp.toString de nuevo a java.sql.Timestamp. Dado element = "2012-08-01 00:00:00.0" and using the code below would return a ParseException diciendo eso element es un Unparseable date.

import java.sql.Timestamp
import java.text.SimpleDateFormat

Timestamp string_timestamp(String element) {        
  if(!date)
    return null 
  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy")
  // error lies here! //
    Date parsedDate = dateFormat.parse(date)
  return new Timestamp(parsedDate.getTime())
}

¿Hay alguna forma de convertir? java.sql.Timestamp.toString() de nuevo a java.sql.Timestamp?

preguntado el 24 de agosto de 12 a las 02:08

3 Respuestas

I think you should simplify your method to be more groovyish. Use the Date class with the groovy extensions.

def string_timestamp(element) {
    def date = Date.parse('yyyy-MM-dd HH:mm:ss.S', element)
    return new Timestamp(date.time)
}

Respondido 24 ago 12, 09:08

Using Date is a bad idea. Date does not handle TimeZone format etc well. See if you can use Calendar Object. Also note that something like date.getYear() will give you 2012-1900 and not the year as you expect. I gave you an example using Date below :a

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

class ABC {

public Timestamp string_timestamp(String element) throws Exception  {        
  //if(!element)
    //return null; 
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
  // error lies here! //
    Date parsedDate = dateFormat.parse(element);
  return new Timestamp(parsedDate.getTime());
}

public static void main(String[] args) throws Exception {
  ABC a = new ABC();
  System.out.println(" Value = " + a.string_timestamp("2012-08-01 01:12:56.0"));
}
}

Respondido 24 ago 12, 03:08

Your input is "2012-08-01 00:00:00.0" correct? Your SimpleDateFormatter is different from what you are using. I will post the code in a few minutes. - naidu ypvs

@DrJava added the code.. also add try catch properly to correctly catch exceptions and also the null checks. Thanks. - naidu ypvs

I know I may be a little late to the party, however I stumbled onto this and thought I'd give my two cents.

El java Timestamp el objeto tiene un static valueOf(String s) método.

Por la API:

static Timestamp    valueOf(String s)
Converts a String object in JDBC timestamp escape format to a Timestamp value.

Note: the string needs to be in JDBC format... So if you parse the date to a different format, you may need to parse it back before calling Timestamp.valueOf(element).

link to api: java.sql.Timestamp

Respondido el 10 de diciembre de 16 a las 20:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.