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.
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).
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.
String start_dt = '2011-01-01'; DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); Date date = (Date)formatter. parse(start_dt);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With