Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Epoch Time

Tags:

java

I have a string startTimestamp which is a string, and I am trying to convert it to a epoch time as follows.

Date starttimesampTime = new Date(Long.parseLong(startTimestamp));

Long epoch = starttimesampTime.getTime() / 1000;

enter image description here

However, I am getting the following exception

java.lang.NumberFormatException: For input string: "2017-10-19 16:18:03.779"

like image 634
casillas Avatar asked Sep 20 '25 20:09

casillas


1 Answers

To get the time, you need to go throw a type which can hold day/year/hour..., you need to parse your String and then get the time :

  • with LocalDatetime, ZonedDateTime :
ZonedDateTime ldate = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
                                   .atZone(ZoneId.of("Europe/Paris"));
long time = ldate.toInstant().toEpochMilli();
System.out.println(time);
  • with Date but it'll need to enhandle ParseException
String str = "2017-10-19 16:18:03.779";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch);

Both will print 1508422683779

like image 143
azro Avatar answered Sep 22 '25 09:09

azro