Frage

Ich habe eine Zeichenfolge, die die enthält Unix -Epoch -Zeit, und ich muss es in ein Java -Date -Objekt umwandeln.

String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
  Date expiry = df.parse(date);
 } catch (ParseException ex) {
  ex.getStackTrace();
}

In der markierten Linie habe ich Probleme. Ich kann nicht herausfinden, was das Argument für SimpleDateFormat () sein sollte oder ob ich SimpledateFormat () verwenden sollte.

War es hilfreich?

Lösung

Wie wäre es mit nur:

Date expiry = new Date(Long.parseLong(date));

Bearbeiten: gemäß RDE6173Die Antwort und einen genaueren Blick auf die in der Frage angegebene Eingabe "1081157732" scheint ein Sekunden-Basis-EPOCH-Wert zu sein, sodass Sie die lange von Parselong () mit 1000 multiplizieren möchten, um in Millisekunden umzuwandeln, was ist, was ist. Was Javas Datumskonstruktor verwendet, also:

Date expiry = new Date(Long.parseLong(date) * 1000);

Andere Tipps

Epoche ist die Anzahl von Sekunden Seit 1. Januar 1970 ..

So:

String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );

Für mehr Informationen:http://www.epochconverter.com/

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)

Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.

To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.

long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)

Hum.... if I am not mistaken, the UNIX Epoch time is actually the same thing as

System.currentTimeMillis()

So writing

try {
    Date expiry = new Date(Long.parseLong(date));
}
catch(NumberFormatException e) {
    // ...
}

should work (and be much faster that date parsing)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top