eishiakonno
eishiakonno

Reputation: 73

PHP timestamp to Java timestamp

I need to convert this 1384174174 timestamp from PHP to Java. This is how I echo the date('Y/m/d H:i:s' ,$dn1['timestamp'] in PHP yet I don't know how to do it in Java. Please help me. Thanks.

Upvotes: 1

Views: 1706

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338516

Avoid legacy classes

The other Answers use terribly-flawed legacy classes that were supplanted by the modern java.time classes built into Java 8+ as defined in JSR 310.

java.time

this 1384174174 timestamp

I presume your input is a count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long input = 1_384_174_174L ;
Instant instant = Instant.ofEpochSecond( input ) ;

To generate text is standard ISO 8601 format, simply call toString. For other formats, use DateTimeFormatter as seen in many many existing Questions & Answers.

See this code run at Ideone.com.

instant.toString(): 2013-11-11T12:49:34Z

Upvotes: 0

Kai Sternad
Kai Sternad

Reputation: 22830

In Java, you'd do it like this:

Date date = new Date(1384174174);
SimpleDateFormat f = new SimpleDateFormat("Y/M/d H:m:s");
String dateFormatted = f.format(date);

Watch out for the format pattern where, unlike PHP, M is month in year and m is minute in hour.

Upvotes: 2

EdgeCase
EdgeCase

Reputation: 4827

This method will take your Unix style date and create a Java Date. It returns a readable string. It should help you get started.

private String unixToString(long unixSeconds) {
    Date date = new Date(unixSeconds);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    return sdf.format(date);
}

Upvotes: 2

Related Questions