Convert from Simple date format (DD/MM/YYYY HH:MM:SS) to Epoch date format

Hello Dears,
I tried to convert date to epoch format with below code but recieved wrong epoch date.

long epochDate = 0;
try {
epochDate = new java.text.SimpleDateFormat(“DD/MM/YYYY HH:MM:SS”).parse(simpleDate).getTime()/1000 ;
} catch (ParseException e) {
e.printStackTrace();
}

	// pipeline
			IDataCursor pipelineCursor_1 = pipeline.getCursor();
			IDataUtil.put( pipelineCursor_1, "epochDate", Long.toString(epochDate) );
			pipelineCursor_1.destroy();

At a quick glance, your pattern seems incorrect. The case of each pattern letter is important. For example, “MM” is equivalent to “month in year” whereas “mm” is “minute in hour”. Trying setting the appropriate pattern first and see if that helps.

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Also, consider passing the pattern in as an input to the service. It it will make your service more reusable. Similarly, consider an input that dictates whether the service returns the epoch in seconds or milliseconds. I see that you’re dividing by 1000 to get seconds, but there are systems that expect the epoch to be in milliseconds so it may help you in the long run to support returning milliseconds as well.

Good luck,
Percio

1 Like

You might consider using DateTimeFormatter instead of SimpleDateFormat. You may also want to consider time zone when interpreting the date/time.

As @Percio_Castro1 notes, likely beneficial to structure your service to be more generic – similar to the built-in services.

You may find this post to be of interest.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.