How to convert a long to a Date with “dd/MM/yyyy”

2019-09-21 23:20发布

问题:

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?

回答1:

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);


回答2:

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);


回答3:

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