Rajeev
Rajeev

Reputation: 559

How to converted timestamp string to a date in java

I have a string "1427241600000" and I want it converted to "yyyy-MM-dd" format.

I have tried, but I am not able to parse it, please review the below code

try {
    String str = "1427241600000";
    SimpleDateFormat sf = new  SimpleDateFormat("yyyy-MM-dd");
    Date date =sf.parse(str);
    System.out.println(date);       
} catch (ParseException e) {
    e.printStackTrace();
}

I would like to know where I went wrong.

Upvotes: 7

Views: 48371

Answers (4)

GopinathSk
GopinathSk

Reputation: 23

You can do it like this:

use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).

DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

Upvotes: 1

Flown
Flown

Reputation: 11740

You should try it the other way around. First get the Date out of the milliTime and then format it.

String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(Long.parseLong(str));
System.out.println(sf.format(date));

Upvotes: 18

user4668606
user4668606

Reputation:

the conversion is highly dependent on what format the timestamp is in. But i assume the whole thing should actually be a long and is simply the systemtime from when the timestamp was created. So this should work:

String str = ...;
Date date = new Date(Long.parseLong(str));

Upvotes: 4

Manish Kothari
Manish Kothari

Reputation: 1712

Use Date date =new Date(Long.parseLong(str)); to convert your String to Date object.

if you are using SimpleDateFormat() the format specified as a parameter to this function should match the format of the date in the String (str in your case). In your case yyyy-MM-dd does not match the format of the time stamp (1427241600000).

Upvotes: 2

Related Questions