This question already has an answer here:
-
Converting long (whose decimal representation represents a yyyyMMdd.. date) to a different date format
2 answers
I have a variable of type Long.
Long longDate = 20180201110400
It represents this: 2018/02/01 11:04:00
I want to convert the format and variable type like below:
Format should be "dd/MM/yyyy" and type should be Date
. How can I do that?
You can covert the long to a Date object first then you can further convert it to your desired format. Below is the code sample.
Long longDate = 20180201110400L;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dateFormat.parse(longDate.toString());
System.out.println("Date : "+date);
SimpleDateFormat dateFormatNew = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = dateFormatNew.format(date);
System.out.println("Formatted date : "+formattedDate);
cast Long to Date:
Long longDate = 20180201110400L;
String dateAsString = String.valueOf(longDate);
Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateAsString);
cast Date to String with "dd/MM/yyyy" format:
String formattedDate = new SimpleDateFormat("dd/MM/yyyy").format(date);
To convert in any standard date format, we can use SimpleDateFormat class. See the below snippet
Long longDate = new Date().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatedDate = dateFormat.format(longDate);
System.out.println(formatedDate);
Output : 01/02/2018