0
        Date date = new Date();
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(s);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Timestamp timestamp=new Timestamp(date.getTime());
        id=Long.parseLong(timestamp.toString());

On executing the above code I got this error:

java.lang.NumberFormatException: For input string: "2018-08-29 16:35:31.753"
    at 
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

What's wrong in it now?

xingbin
  • 27,410
  • 9
  • 53
  • 103
Shubham Garg
  • 37
  • 1
  • 1
  • 7
  • 3
    `timestamp.toString()` returns "2018-08-29 16:35:31.753" - you can't use `Long.parseLong` on that. What are you actually trying to do? – greg-449 Aug 29 '18 at 11:22
  • As greg-449 says, you're parsing a date string to a long variable, this isn't working as you need to set a long representation in a string variable. If you're trying to get the milliseconds, you need to use `long id = date.getTime(); ` – F10 Aug 29 '18 at 12:27
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Aug 29 '18 at 14:03
  • Possible duplicate of [How to convert a string Date to long millseconds](https://stackoverflow.com/questions/12473550/how-to-convert-a-string-date-to-long-millseconds). Please search, and you will find many more helpful questions and answers. – Ole V.V. Aug 29 '18 at 14:08
  • `LocalDateTime.parse("2018-08-29 16:35:31.753".replace(' ', 'T')).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()`. On my computer it gave (all odd digits) 1 535 553 331 753, but the result depends on the time zone. – Ole V.V. Aug 29 '18 at 14:41

1 Answers1

2

The error happens when you try to get long value by Timestamp.toString(), since it returns 2018-08-29 16:35:31.753, which is not a valid long.

Just use:

long id = timestamp.getTime();
xingbin
  • 27,410
  • 9
  • 53
  • 103