0

I got a date/time format data from http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour

here's a quote of data:

"properties":{
    "mag":0.5,
    "place":"123km NNW of Talkeetna, Alaska",
    "time":1343795877,
    "tz":-480,
    "url":"/earthquakes/eventpage/ak10523664",
    "felt":null,
    "cdi":null,
    "mmi":null,
    "alert":null,
    "status":"AUTOMATIC",
    "tsunami":null,
    "sig":"4",
    "net":"ak",
    "code":"10523664",
    "ids":",ak10523664,",
    "sources":",ak,",
    "types":",general-link,general-link,geoserve,nearby-cities,origin,"
},

but when I use:

Date date1 = new Date();
date1.setTime("1343795877"); 

the result is: Fri Jan 16 13:16:35 GMT+00:00 1970 but the correct date is Wednesday, August 01, 2012 04:37:57 UTC (from CSV version of the same website)

How can I get the correct time??

Hinata
  • 43
  • 6

3 Answers3

2

The number "1343795877" is unix time - time in seconds that elapsed since 1970.

You need to multiply it by 1000 because it is time in seconds and Date constructor takes milliseconds. So this will do the magic:

Date d = new Date(1343795877*1000);

You can use online UNIX to Date converter to check it.

Bear in mind that UNIX time is in UTC and it does not mimic user timezone - so you will need to apply your timezone.

I suggest you to work with JodaTime it is really handy.

Here is an example of the conversion.:

DateTime dt = new DateTime(1343795877*1000);
dt.withZone(DateTimeZone.forID("UTC"));

EDIT:

DateTimeFormatter formatter = 
    DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss, SSS [z]");
formatter.print(dt);
aviad
  • 8,229
  • 9
  • 50
  • 98
1

First of all your syntax is wrong. Date have no method such as date.setTime(String). Its date.setTime(Long) which takes milliseconds as argument. And what you are getting is seconds so just multiply it by 1000 to get correct date. So your solution is date1.setTime(1343795877000L);

Abhishek bhutra
  • 1,400
  • 1
  • 11
  • 29
1

Have a look here its simply :

new Date(epochTime * epochFormat) // '1343795877' this time format is known as epoch time

epochTime is time of long type eg. 1343795877L
epochFormat is 1000 if epochTime is in seconds else 1 if in milliseconds

In your case its in seconds so multiply by 1000

I think you should also use SimpleDateFormatter to format your date :

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yy", Locale.ENGLISH); // date format and locale you want to use
dateFormat.setTimeZone("Asia/Kolkata"); // can have your time zone
String date = dateFormat.format(new Date(epochTime * epochFormat));

for date formats look here

Harmeet Singh
  • 2,555
  • 18
  • 21