Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 645
Rajeev Avatar asked Mar 25 '15 13:03

Rajeev


People also ask

How do I convert timestamp to Date?

The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package).

Can I convert a string in to a Date in Java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes. To learn this concept well, you should visit DateFormat and SimpleDateFormat classes.

How do I convert a string to a Date?

String start_dt = '2011-01-01'; DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); Date date = (Date)formatter. parse(start_dt);


1 Answers

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));
like image 126
Flown Avatar answered Oct 06 '22 01:10

Flown