2
\$\begingroup\$

I have this method in Java:

private static int ConvertToTimestamp(Date value)
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S", Locale.US);
    String text = "1970-01-01 00:00:00.0";
    LocalDateTime localDateTime = LocalDateTime.parse(text, formatter);

    // getTime() returns milliseconds
    int seconds = (int) (value.getTime()/1000) - localDateTime.getSecond();
    return seconds;

}

It returns the number of seconds between the input parameter and 1/1/1970. Are there any improvements to this or better ways to do it?

\$\endgroup\$
  • \$\begingroup\$ How exactly is this different from simply calling value.getTime() / 1000? \$\endgroup\$ – Greg Hewgill Dec 14 '16 at 22:40
1
\$\begingroup\$

value.getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by a Date object.

You don't need a ConvertToTimestamp method, just call value.getTime() / 1000 to get the seconds.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.