Aliaxander
Aliaxander

Reputation: 2617

Conversion from "datetime-local" to java.sql.Timestamp

I have a form with input of type "datetime-local" on a jsp page, the data is passed to a servlet:

String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME);

How to convert the input to java.sql.Timestamp?

Upvotes: 0

Views: 8555

Answers (2)

Olivier Levrey
Olivier Levrey

Reputation: 115

Cyphrags' answer won't work if seconds are set to "00", because Chrome won't send the seconds part resulting in a java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] when calling Timestamp.valueOf().

Therefore a more complete answer could be:

String datetimeLocal = "1985-04-12T23:20";
// make sure the seconds are set before parsing
if (StringUtils.countMatches(datetimelocal, ":") == 1) {
    datetimelocal += ":00";
}
Timestamp value = Timestamp.valueOf(datetimeLocal.replace("T", " "));

Upvotes: 2

Cyphrags
Cyphrags

Reputation: 528

EDIT: Well, I found something new!

You can use Timestamp.valueOf() to format a time-string with the value of yyyy-[m]m-[d]d hh:mm:ss[.f...] So it can also handle micro/nano seconds. The only thing you need to do is replace the T with a space.

This works:

String datetimeLocal = "1985-04-12T23:20:50.52";
System.out.println(Timestamp.valueOf(datetimeLocal.replace("T"," ")));

The output:

1985-04-12 23:20:50.52

According to this site your resetTimeString looks like this: '1985-04-12T23:20:50.52' (a string)

I couldn't find a method to convert this to a timestamp directly, but you could just split it up manually:

String[] dateTime = datetimeLocal.split("T");
String[] date = dateTime[0].split("-");
String[] time = dateTime[1].split(":");

This will print:

System.out.println("DateTime: " + Arrays.toString(dateTime));
System.out.println("Date: " + Arrays.toString(date));
System.out.println("Time: " + Arrays.toString(time));

>>> DateTime: [1985-04-12, 23:20:50]
>>> Date: [1985, 04, 12]
>>> Time: [23, 20, 50]

After that you could just create a new Timestamp: (This is deprecated!)

Timestamp stamp = new Timestamp(Integer.valueOf(date[0]).intValue() - 1900, 
            Integer.valueOf(date[1]).intValue(), 
            Integer.valueOf(date[2]).intValue(), 
            Integer.valueOf(time[0]).intValue(), 
            Integer.valueOf(time[1]).intValue(), 
            Integer.valueOf(time[2].split("\\.")[0]).intValue(), 
            Integer.valueOf(time[2].split("\\.")[1]).intValue());

Note that, if you use this you need to subtract '1900' from the year and split dots with \\.

Also, you'd need to handle nanoseconds (In my example I'm using the value 50.52 as seconds, but the string returned from your server might not contain the nanoseconds)

You could also calculate a long from the date and use new Timestamp(<long>)

I hope this helps :)

Upvotes: 3

Related Questions